100 XP

96. Fast power

Advanced math recursion

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 ** or pow(). The exponent can be as large as 10^18, so multiplying by base that 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, and b^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

Inputbase = 2, exponent = 10, modulus = 1000
Output24
Explanation2^10 is 1024; its remainder by 1000 is 24.

Example 2

Inputbase = 3, exponent = 0, modulus = 7
Output1
ExplanationAnything to the power 0 is 1.

Example 3

Inputbase = 7, exponent = 1000000000000000, modulus = 13
Output9
Explanation50 halvings, not 10^15 multiplications.

Constraints

  • base is a whole number from 0 to 10^9.
  • exponent is a whole number from 0 to 10^18.
  • modulus is a whole number from 1 to 10^9.

Submit also runs 9 more tests you can't see.

Practises Recursion (lesson 20).

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