Recursive Algorithm: n factorial

Discussion

The function call Factorial(4) should have value 24, because that is 4 * 3 * 2 * 1 .


For a situation in which the answer is known, the value of 0! is 1.

base case

if ( number == 0 ) return 1;

general case

The value of  Factorial(n)  can be written as
    n  *  the product of the numbers from (n - 1) to 1,
    that is:  
		       n   *   (n - 1)  *  .  .  .  *  1

or, n * Factorial(n - 1)
And notice that the recursive call Factorial(n - 1) gets us “closer” to the base case of Factorial(0).
 

Solution

int Factorial ( int number )		
// Pre: number is assigned and number >= 0.
{
     if ( number == 0)			//  base case
	     return  1 ;
	   else					// general case	
		 return  number + Factorial ( number - 1 ) ;
}

 


 

 

 

© Lynne Grewe