Data Structures, Algorithms, & Applications in Java
Chapter 2, Exercise 7

The nonrecursive method is applications.IterativeFactorial.factorial . The code is given below.


/** return n! */
public static int factorial (int n)
{
   if (n <= 1)
      return 1;
   int fact = 2;
   for (int i = 3; i <= n; i++)
      fact *= i;
   return fact;
}



For this nonrecursive method, Sfactorial(n) = 0 while the space requirements of the recursive version are 4 * max{n, 1}. The nonrecursive version uses less space than its recursive counterpart.