天天看點

階乘遞歸算法

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));      

繼續閱讀