Code //阶乘递归算法(计算n个数的组合) function CalFactorial(n) { if (n <0) { return'n不能为负数'; } elseif (n ==0) { return1; } 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. return1.; } 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));
posted on
2009-11-05 23:16封起De日子
阅读(97)
评论(0)
编辑收藏举报