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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With