Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do powerOf(int x, int n)?

So given x, and power, n, solve for X^n. There's the easy way that's O(n)... I can get it down to O(n/2), by doing

numSquares = n/2;
numOnes = n%2;
return (numSquares * x * x + numOnes * x);

Now there's a O(log(n)) solution, does anyone know how to do it? It can be done recursively.

like image 399
SIr Codealot Avatar asked Mar 30 '10 02:03

SIr Codealot


People also ask

How do you find the power of a number efficiently?

Exponentiation by Squaring or Binary Exponentiation Idea is to the divide the power in half at each step. Effectively, power is divided by 2 and base is multiplied to itself. So we can write 3 ^ 10 = 9 ^ 5 . Effectively, when power is not divisible by 2, we make power even by taking out the extra 9.

How do you raise a number to a power in C++?

pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function. then two numbers are passed. Example – pow(4 , 2); Then we will get the result as 4^2, which is 16.


1 Answers

Well, you know that xa+b = xa xb so...

int pow(int x, unsigned int y)
{
  if (y == 0) return 1;
  if (y == 1) return x;
  int a = y / 2;
  int xa = pow(x, a);
  if (a + a == y) // y even
    return xa * xa;
  else
    return xa * xa * x;
}
like image 79
Peter Alexander Avatar answered Oct 05 '22 18:10

Peter Alexander