Friday, January 29, 2016

Power

Power


Find x to the power n in efficient way. Assume that x>=0 and n>=0.


Sol:
1
2
3
4
5
6
7
8
9
10
11
  int power(int x, int n)
   {
    if(n <= 0)
        return 1;
    else if(n == 1)
        return x;
    else if(n%2 == 0)
        return power(x*x, n/2);
    else
        return x*power(x*x, n/2);
}
If x is double and n is integer
1
2
3
4
5
6
7
8
9
10
11
public static double power(double xint n
{
  if(n<0){
      return 1/(x* power(x, -(++n)));
   }
   else if(n == 0) {
       return 1;
   }
   else {
       return (n%2 == 0) ? power(x*x, n/2) : x* power(x*x, n/2);
   }
}

No comments:

Post a Comment