Recursive algorithms


coputepower

Recursion


In this article
1- What is a Recursive function and the problem it solve?
2- Example Computing Powers .

Recursive function

A Recursive function is a function that calls itself ether directly or indirectly through another function .A Recursive function is called to solve a problem by solving a smaller instance of the same problem unless it is the simplest case(s) or so-called base case(s) it will return the result.


Example Computing Powers

1 - The simplest case when you want to compute x^n is when n = 0 the result always be 1 no matter what x is .

function CopmutePower(x , n){
 if (n == 0){
   return 1;
  }


}

2 - The second case we can think about is when n is positive

when you multiply powers of  x you add the exponents: x^a *  x^b =  x^(a+b)
 eg. 2^2 × 2^4 = 2^(2+4) = 64.

If n is positive and even then  x^​n ​​= x^(​n/2) ​​ * x^(​n/2)
 eg. 2^6 = 2^(6/2) * 2^(6/2) = 64   and for y= x^(n/2) Therefore x^n = y * y

function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

}


3 -If n is positive and odd then x^​n ​​= x^(​n−1) ​​ * x  in this case if n-1 = 0 then it will be the base case when n = 0  and if n-1  is positive and even  then it will be the second case .
Therefor you could compute those cases recursively 

function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive and even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

   // n is positive and even
    if (!(n % 2 == 0)){
     return x * CopmutePower(x, n - 1);       
   }


}

4 - If n is negative then x^n = 1 / (x^n)


function CopmutePower(x , n){
  // n = 0 Simplest case(base case)
 if (n == 0){
   return 1;
  }

  // n is positive and even
  if (n % 2 == 0){
  var y = CopmutePower(x, n / 2);
  return y * y;
  }

   // n is positive and even
    if (!(n % 2 == 0)){
     return x * CopmutePower(x, n - 1);       
   }
 
     //  n is negative
    if (n < 0){
     return 1 / CopmutePower(x, -n);       
   }

}

-- JavaScript Code
See the Pen Recursive powers by Mohamed Salah (@saad306) on CodePen.

-- C# Code