Recursive Algorithm: Power of

Discussion

From mathematics, we know that

	2^0  =  1     and      2^5  = 	2 * 2^4  

In general,  

    x^0  =  1     and      x^n  = 	x * x^n-1  
                                for integer  x, and integer n > 0.


Here we are defining  xn  recursively, in terms of  x^(n-1) 

base case

x^0 = 1;

general case

x^n  = 	x * x^n-1 

Solution

// Recursive definition of power function 


int  Power (  int   x,   int   n )	
	
	//  Pre:     n >= 0.   x, n are not both zero
	//  Post:   Function value = x raised to the power n.

{
	if ( n == 0 )
       return  1; 		//  base case
	else                       // general case
       return (  x * Power ( x , n-1 ) ) ;

} 	

 


 

 

 

© Lynne Grewe