Monday, June 27, 2011

Efficient Way to Calculate Power(x,y)

Problem: Give your own implementation of power(x,y), where y is a nature number.

Solution: There is a neat solution:

double power(double base, int exp)
{
   int res = 1;
   
   while(exp)
   {
     if(exp & 1) res *= base;

     exp >>= 1;
     base *= base;
   }

   return res;
}

No comments:

Post a Comment