Skip to contentKEEP THE CRAFTTHE SANCTUARY

Compute Modular Power

Compute base^exponent % modulus in O(log exponent) steps with fast exponentiation by squaring.

The problem

Implement modular_power(base, exponent, modulus) and return base^exponent % modulus. exponent is 0 or more and modulus is at least 1. base may be negative; the answer is always between 0 and modulus - 1, like Python's % operator. Exponents can be large, so take O(log exponent) steps instead of multiplying exponent times. Example: modular_power(2, 10, 1000) is 1024 % 1000 = 24, and modular_power(5, 0, 1) is 0, because every number % 1 is 0. Do not use ** or pow with three arguments.

Starter code

def modular_power(base, exponent, modulus):
    pass

Public examples

  1. base = 7, exponent = 128, modulus = 13gives3
  2. base = 5, exponent = 0, modulus = 1gives0

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.