阶乘递归算法

Code
//阶乘递归算法(计算n个数的组合)
functionCalFactorial(n)
{
if(n<0)
{
return'n不能为负数';
}
elseif(n==0)
{
return1;
}
else
{
returnn*CalFactorial(n-1);
}
}

functionfactorialWork(aNumber,recursNumber){
//recursNumberkeepstrackofthenumberofiterationssofar.
if(aNumber==0){//Ifthenumberis0,itsfactorialis1.
return1.;
}
else{
if(recursNumber>100){
return("Toomanylevelsofrecursion.");
}
else{//Otherwise,recurseagain.
return(aNumber*factorialWork(aNumber-1,recursNumber+1));
}
}
}

functionfactorial(aNumber){
//Usetypeannotationtoonlyacceptnumberscoercibletointegers.
//doubleisusedforthereturntypetoallowverylargenumberstobereturned.
if(aNumber<0){
return("Cannottakethefactorialofanegativenumber.");
}
else{//Calltherecursivefunction.
returnfactorialWork(aNumber,0);
}
}

//Callthefactorialfunctionfortwovalues.
alert(factorial(5));
alert(factorial(
80));

你可能感兴趣的:(算法)