Overflow-Safe Power with a Custom Modular Multiplier
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Tests whether a candidate can build exponentiation from scratch using only 64-bit-safe addition and multiplication under an arbitrary modulus.
Overflow-Safe Modular Exponentiation
You are working in an environment where integers are limited to 64 bits. Your task is to compute (base ^ exp) mod m without letting any intermediate value exceed 64 bits.
The challenge
When base and exp are both close to 2^61 − 1, a naive base * exp can require up to 122 bits — far beyond a 64-bit register. You must build your solution from the ground up so that every intermediate value stays within 64 bits, just as it would have to in C, C++, Java, or Go.
Build your solution in three layers:
Layer 1 — overflow-safe addition under a modulus
Given x, y ∈ [0, m), return (x + y) mod m. You may not compute x + y directly when the sum could reach or exceed 2^64. Instead, use a comparison-and-subtract strategy that keeps all values below m.
Layer 2 — overflow-safe multiplication under a modulus
Given x, y ∈ [0, m), return (x * y) mod m. Use a binary "double-and-add" loop (analogous to the peasant multiplication algorithm): process the bits of y one at a time, doubling x with your safe addition helper and accumulating into a result.
Layer 3 — fast exponentiation
Given base, exp, and m, return (base ^ exp) mod m. Use a square-and-multiply loop: process the bits of exp one at a time, squaring base with your safe multiplication helper and accumulating into a result.
Rules
- All three layers must call only the layer below them for any potentially large arithmetic — no plain
*or+between values that could be nearmunless they are already known to be small. - You may assume Python's unbounded integers for the purposes of this problem, but you must enforce the 64-bit discipline yourself: every value passed into or produced by your helpers must stay in
[0, m).
Edge-case rules
exp = 0returns1 % mfor anybase, includingbase = 0(the convention0^0 = 1applies).m = 1always returns0.base >= mmust be reduced tobase % mbefore the first multiplication.
Constraints
0 ≤ base < 2^61 − 10 ≤ exp < 2^61 − 11 ≤ m < 2^61 − 1- Inputs are integers; the return value is an integer in
[0, m).
Examples
Example 1
Input: modular_pow(2, 10, 1000)
Output: 24
Example 2
Input: modular_pow(3, 0, 7)
Output: 1
Example 3
Input: modular_pow(10, 3, 6)
Output: 4
Hints
Hint 1
For safe addition of x and y both in [0, m), check whether x >= m - y instead of computing x + y directly. If true, the answer is x - (m - y); otherwise it is x + y. No intermediate ever leaves [0, m].
Hint 2
For safe multiplication, write a loop over the bits of y. Maintain a running double of x (using your safe add) and a running result. When the current low bit of y is set, add the current x into result. This is the same idea as left-to-right binary exponentiation, but for multiplication.
Hint 3
For exponentiation, mirror the multiplication loop exactly one level up: loop over the bits of exp, maintain a squaring base (using your safe multiply), and accumulate into result when a bit is set. Initialise result to 1 % m so the m = 1 edge case is handled automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution stacks three routines, each built from the one below it. The discipline enforced throughout is: every value entering or leaving a helper must lie in [0, m).
Layer 1 — add_mod(x, y)
For x, y ∈ [0, m) the true sum lies in [0, 2m − 2]. Computing (x + y) % m is unsafe in a 64-bit world when m is near 2^63. Instead, check whether x >= m - y, which is equivalent to x + y >= m. If true, return x - (m - y) (same as x + y - m, but never forms the oversized sum). Otherwise return x + y, which is already below m. Every value produced stays in [0, m - 1].
Layer 2 — multiply_mod(x, y)
Decompose y in binary: x · y = Σ x · 2^i over the set bits of y. Maintain a variable that holds x · 2^i mod m by doubling with add_mod(x, x) on each iteration. Whenever the low bit of y is 1, accumulate the current x into result via add_mod. The guard if y: before the doubling step skips one unnecessary add_mod call on the final iteration. Because both result and x always lie in [0, m), add_mod is always called with valid inputs.
Layer 3 — modular_pow
Mirrors multiply_mod exactly, one level up: base ^ exp = Π base ^ (2^i) over the set bits of exp. Square cur_base with multiply_mod(cur_base, cur_base) each step, and fold it into result with multiply_mod(result, cur_base) when the low bit of exp is set.
Initialising result = 1 % m rather than 1 handles m = 1 uniformly (any value mod 1 is 0). Reducing base % m at the start ensures cur_base enters the loop already in [0, m).
Why it is correct
add_mod: x >= m - y ↔ x + y >= m. The two branches cover the full range [0, 2m − 2] without overlap and both land in [0, m − 1]. ✓
multiply_mod: The loop invariant is result + x · y ≡ x₀ · y₀ (mod m). Moving a bit from y into result (when odd) then halving y while doubling x preserves the invariant. At y = 0, result ≡ x₀ · y₀. ✓
modular_pow: The loop invariant is result · cur_base ^ exp ≡ base ^ exp₀ (mod m). The same square-and-multiply argument applies. At exp = 0, result ≡ base ^ exp₀. ✓
Edge cases
| Situation | Behaviour |
|---|---|
m = 1 | 1 % m = 0; base % m = 0; loop returns 0 |
exp = 0 | Loop body never runs; returns 1 % m |
base = 0, exp > 0 | cur_base = 0; all multiplications yield 0 |
base >= m | Reduced immediately with base % m |
Values near 2^61 − 1 | All intermediates bounded by m − 1 < 2^61 − 1 |
Complexity
Let B = log₂(exp) and K = log₂(m), both at most 61.
| Routine | Time | Space |
|---|---|---|
add_mod | O(1) | O(1) |
multiply_mod | O(K) calls to add_mod | O(1) |
modular_pow | O(B) calls to multiply_mod → O(B · K) | O(1) |
In the worst case this is about 61 × 61 ≈ 3 700 constant-time steps. Space is O(1) because only a handful of scalars are kept and there is no recursion.
Reference solution
def modular_pow(base: int, exp: int, m: int) -> int:
def add_mod(x: int, y: int) -> int:
# x, y in [0, m). Avoid computing x + y which could reach 2m - 2.
# x >= m - y iff x + y >= m, so we subtract instead of adding.
if x >= m - y:
return x - (m - y)
return x + y
def multiply_mod(x: int, y: int) -> int:
# Double-and-add: process bits of y, doubling x each step.
result = 0
while y:
if y & 1:
result = add_mod(result, x)
y >>= 1
if y: # skip the last double (never used)
x = add_mod(x, x)
return result
# Square-and-multiply: process bits of exp, squaring base each step.
result = 1 % m # handles m = 1 uniformly (gives 0)
cur_base = base % m # reduce base into [0, m) before first use
while exp:
if exp & 1:
result = multiply_mod(result, cur_base)
exp >>= 1
if exp: # skip the last square (never used)
cur_base = multiply_mod(cur_base, cur_base)
return result