Modular Exponentiation Tower (Tetration mod M)
Math & Bit ManipulationAuto-graded · 18 test casesLast updated
Tests mastery of modular arithmetic by computing a power tower (iterated exponentiation) modulo M using Euler's theorem and recursive modular exponentiation.
Modular Power Tower
A power tower of height h for a base a is defined as:
tower(a, 0) = 1
tower(a, 1) = a
tower(a, 2) = a^a
tower(a, 3) = a^(a^a)
...
tower(a, h) = a ^ tower(a, h-1)
In other words, it is a exponentiated by itself h times (right-associative).
Because these numbers grow astronomically fast, you must compute the result modulo M:
result = tower(a, h) mod M
Your Task
Implement power_tower_mod(a, h, m) that returns tower(a, h) mod m.
Key Facts You May Need
- Euler's theorem: For any integer
nwithgcd(a, n) = 1:
a^x ≡ a^(x mod φ(n)) (mod n)
whereφis Euler's totient function. - A generalised version (due to Euler/lifting-the-exponent) handles the case when
gcd(a, n) > 1:
a^x ≡ a^(φ(n) + (x mod φ(n))) (mod n)providedx ≥ φ(n). - The recursion bottoms out quickly because
φ(n) < nforn > 1, soφapplied repeatedly reaches 1 withinO(log n)steps.
Constraints
2 ≤ a ≤ 100 ≤ h ≤ 1002 ≤ m ≤ 10^6- When
h = 0, the tower equals1by convention, so the answer is1 mod m. - When
m = 1, the answer is always0. - You may assume
a ≥ 2, so the tower grows without bound forh ≥ 2(you must use modular reduction, not compute the raw value).
Examples
Example 1
Input: power_tower_mod(2, 3, 1000)
Output: 16
Example 2
Input: power_tower_mod(3, 2, 7)
Output: 6
Example 3
Input: power_tower_mod(2, 0, 999)
Output: 1
Hints
Hint 1
Start by implementing Euler's totient function φ(n); notice that repeatedly applying φ reaches 1 in O(log n) steps, which bounds your recursion depth regardless of h.
Hint 2
Use the generalised Euler theorem: a^x mod n = a^(phi(n) + x mod phi(n)) mod n when x >= phi(n); you need to track whether the true exponent is 'large enough' (>= phi(n)) separately from its residue.
Hint 3
Combine pow(a, e, m) (Python's built-in three-argument power) with your recursive exponent reduction; the recursion on m shrinks quickly, so even h=100 terminates instantly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Idea
The power tower a^a^a^... (height h) grows so fast that we cannot compute it directly for even modest values. Instead, we reduce the exponent modulo φ(m) using Euler's theorem, recurse until the modulus shrinks to 1, then unwind.
Euler's Theorem (Generalised)
For any integers a, x, n with n ≥ 1:
- If
gcd(a, n) = 1:a^x ≡ a^(x mod φ(n)) (mod n) - If
gcd(a, n) > 1butx ≥ φ(n):a^x ≡ a^(φ(n) + x mod φ(n)) (mod n)
The second case is the "lifting" generalisation. It requires knowing whether the true exponent x is at least φ(n), not just its residue.
Algorithm
We define a recursive function solve(a, h, m) returning (val, large) where val = tower(a,h) mod m and large is a boolean indicating whether the true tower value is ≥ m.
Base cases:
m = 1: return(0, True).h = 0: tower is1, return(1 % m, 1 >= m).h = 1: tower isa, return(a % m, a >= m).
Recursive step for h ≥ 2:
- Compute
φ(m). - Recurse:
(e_mod_phi, e_is_large) = solve(a, h-1, φ(m)). - If
e_is_large(the true exponentE ≥ φ(m)), use exponentφ(m) + e_mod_phi(generalised formula).
Otherwise usee_mod_phidirectly (true value is small enough). - Return
pow(a, exp, m)using Python's fast three-argument built-in.
Why It Terminates Quickly
φ(m) < m for all m > 1, and φ applied repeatedly reaches 1 in O(log m) steps. Combined with the fact that for h ≥ 2 and a ≥ 2 the tower quickly exceeds any fixed modulus threshold, the recursion on m bottoms out in at most O(log m) levels regardless of h.
Complexity
- Time:
O(log²m · √m)— at mostO(log m)recursive levels, each callingeuler_totientinO(√m)andpow(a, e, m)inO(log e · log²m). - Space:
O(log m)recursion stack.
For m ≤ 10^6 this is well within limits.
Reference Solution
from math import gcd
def power_tower_mod(a: int, h: int, m: int) -> int:
def euler_totient(n: int) -> int:
result = n
p = 2
temp = n
while p * p <= temp:
if temp % p == 0:
while temp % p == 0:
temp //= p
result -= result // p
p += 1
if temp > 1:
result -= result // temp
return result
def solve(a: int, h: int, m: int):
if m == 1:
return (0, True)
if h == 0:
return (1 % m, 1 >= m)
if h == 1:
return (a % m, a >= m)
phi = euler_totient(m)
e_mod_phi, e_is_large = solve(a, h - 1, phi)
if e_is_large:
exp = phi + e_mod_phi
else:
exp = e_mod_phi
val = pow(a, exp, m)
import math
if exp == 0:
raw_large = (1 >= m)
else:
raw_large = (exp * math.log(a) >= math.log(m))
return (val, raw_large)
result, _ = solve(a, h, m)
return result