Raising to a power without multiplying that many times
MediumStuck?
Show a hintHide the hint
The answer for n is the answer for n/2 squared, times x when n is odd. Compute the half once and square it, or you have gained nothing.
The idea behind this problem
Next in this lesson
Turn the list aroundCompute x to the power of n, reported modulo 1000000007.
The modulus is there because the real answer is astronomically large: 2 to the power of a billion has about 300 million digits. Taking a remainder at every step keeps the numbers small without changing the answer, since a remainder survives multiplication.
Worked example#
2 to the power of 10 is 1024.
3 to the power of 5 is 243.
The idea#
Multiplying x by itself n times takes n multiplications. With n around a billion, that is a billion multiplications and the judge stops you.
The way out is one observation:
x to the n = (x to the n/2) squared, when n is even
= (x to the n/2) squared × x, when n is odd
Compute the half once and square it. Do not compute it twice, which is the mistake that turns this back into n multiplications wearing a disguise:
half = power(x, n / 2) # once
return half * half # then square it
Each step halves n, so it finishes in about log n multiplications. For a billion that is thirty, not a billion.
Why the base case is 1#
x to the power of zero is 1, and that is not a convention chosen to be tidy. It is the value that makes the squaring work: one more halving of an exponent of 1 gives 0, and the answer has to be the multiplicative identity for 1 × 1 × x to come out as x.
The recursion is genuinely worth it here#
Most of the recursions you have written could have been loops. This one can too, by reading the bits of n, but the recursive version is the one that states the idea: the answer for n is the answer for n/2, squared. Writing it that way first and converting later is the right order.
Constraints#
0 <= x <= 10000000000 <= n <= 1000000000
Input
x is a single integer, then n on the next line.
Output
Print x to the power of n, modulo 1000000007.
Examples
Input
2 10
Output
1024
Two to the tenth is 1024, well under the modulus.
Input
3 5
Output
243
Three to the fifth is 243.
Input
5 0
Output
1
Anything to the power of zero is one.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.