-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第50天 请写出一个函数求出N的阶乘(即N!) #191
Comments
|
function getTotal(n){
let s = 1,total;
while(s<=n){
total = 1*s;
s++;
}
return total
} |
const stepNum = (num) => (num === 1 ? num : num * stepNum(num - 1));
console.log(stepNum(3))
console.log(stepNum(4))
console.log(stepNum(5))
console.log(stepNum(6)) |
|
推荐这种写法,进行了尾递归优化,数值很大也不会出现内存溢出的问题 |
const getFactorial = n => {
return new Array(n-1).join(',').split(',').reduce( total => { --n; return total*n}, n)
} |
function getN(num) {
return Array.from(new Array(num)).reduce((cacheNum, it, index) => {
return cacheNum * (index + 1);
}, 1);
}
console.log(getN(6)); |
const factorial = num => {
if (num > 1)
return num * factorial(num - 1)
return 1
}
console.log(factorial(5)) |
while( n>=1 ){ |
这好像都没考虑位数限制 |
判断了下如果小于0以及其他因素。 function factorial(num) {
let data = num;
if (num < 0) return -1;
if (num === 0 || num === 1) return 1;
while (num > 1) {
num--;
data *= num;
}
return data;
}
console.log(factorial(5)); // 120 |
function getNum (num) { |
|
正常递归会爆栈,所以要动态规划 }; |
function tailDiGui(n, r) {
if (n === 1) {
return r;
} else {
return tailDiGui(n - 1, r * n)
}
}
function jieCheng(n) {
return tailDiGui(n, 1)
}
console.log(jieCheng(100)); |
function factorial(n) {
if (isFinite(n) && n > 0 && Math.round(n)) {
if (!(n in factorial)) {
factorial[n] = n * factorial(n - 1)
}
return factorial[n]
} else {
return NaN;
}
}
factorial[1] = 1;
console.log(factorial(1000)); |
|
上面这个不行, |
function factorial(num, sum = 1) { |
function factorial (n) {
if (n > 1) {
return n * factorial(n - 1)
}
return 1
}
factorial(0) // 1
factorial(5) // 120 |
第50天 请写出一个函数求出N的阶乘(即N!)
The text was updated successfully, but these errors were encountered: