96. Fast power
Write a function power_mod(base, exponent, modulus) that returns base to the power exponent, modulo modulus:
the remainder of base ** exponent divided by modulus. Calculations like this are at the heart of encryption.
- Don't use
**orpow(). The exponent can be as large as 10^18, so multiplying bybasethat many times would never finish, and the full power would have more digits than there are atoms in the universe. - Two facts make it fast. Squaring halves the exponent:
b^10 = (b^5)^2, andb^11 = (b^5)^2 * b. And remainders can be taken at every step without changing the answer, which keeps the numbers small. - Any number to the power 0 is 1, including 0 to the power 0, so the answer is then
1 % modulus(0 when the modulus is 1).
Example 1
Input
base = 2, exponent = 10, modulus = 1000Output
24Explanation2^10 is 1024; its remainder by 1000 is 24.
Example 2
Input
base = 3, exponent = 0, modulus = 7Output
1ExplanationAnything to the power 0 is 1.
Example 3
Input
base = 7, exponent = 1000000000000000,
modulus = 13Output
9Explanation50 halvings, not 10^15 multiplications.
Constraints
baseis a whole number from 0 to 10^9.exponentis a whole number from 0 to 10^18.modulusis a whole number from 1 to 10^9.
Submit also runs 9 more tests you can't see.
Practises Recursion (lesson 20).
- Write it recursively. The power for
exponentcomes from the power forexponent // 2: square that result, and multiply bybaseonce more if the exponent is odd. - The recursion stops at an exponent of 0, whose answer is
1 % modulus, not just 1: with a modulus of 1 every remainder is 0. - Take
% modulusafter every multiplication, so the numbers never grow past modulus squared. Each call halves the exponent, so 10^18 takes about 60 calls.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def power_mod(base, exponent, modulus):
"""Work out base ** exponent % modulus, quickly.
base: int, 0 or more
exponent: int, 0 or more, possibly huge
modulus: int, 1 or more
Returns: int, the remainder of base^exponent divided
by modulus
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.