Code
//阶乘递归算法(计算n个数的组合)
function CalFactorial(n)
{
if (n < 0)
{
return 'n不能为负数';
}
else if (n == 0)
{
return 1;
}
else
{
return n * CalFactorial(n - 1);
}
}
function factorialWork(aNumber, recursNumber) {
// recursNumber keeps track of the number of iterations so far.
if (aNumber == 0) { // If the number is 0, its factorial is 1.
return 1.;
} else {
if(recursNumber > 100) {
return("Too many levels of recursion.");
} else { // Otherwise, recurse again.
return (aNumber * factorialWork(aNumber - 1, recursNumber + 1));
}
}
}
function factorial(aNumber) {
// Use type annotation to only accept numbers coercible to integers.
// double is used for the return type to allow very large numbers to be returned.
if(aNumber < 0) {
return("Cannot take the factorial of a negative number.");
} else { // Call the recursive function.
return factorialWork(aNumber, 0);
}
}
// Call the factorial function for two values.
alert(factorial(5));
alert(factorial(80));
阶乘递归算法
原创
©著作权归作者所有:来自51CTO博客作者DickyNet的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java递归算法阶乘 java递归阶乘代码
下面要给大家讲到的就是和java递归求阶乘相关的内容,那么你知道应该如何实现吗?一起通过下面的例子来详细的了解吧。
java递归算法阶乘 java阶乘递归 递归 java i++ -
java 阶乘递归 java递归阶乘图解
Java支持递归。递归是根据自身定义内容的过程。就java编程而言,递归是一个允许方法调用自身的特征。调用自身的方法被称为递归方法。
java 阶乘递归 递归 递归方法 Test