How to evalute an exponential tower modulo a prime
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
An exponential tower (also called a power tower or tetration) is an expression like a^(b^(c^d)), evaluated from the top down (right to left). Computing such towers modulo a prime is a classic number theory problem that appears in competitive programming and cryptography. Naive computation is impossible because the intermediate values grow astronomically, but Euler's theorem provides an efficient recursive approach.
Key Concepts
Euler's Theorem
For any integer a and prime p where gcd(a, p) = 1:
This means the exponent can be reduced modulo p-1 (which is Euler's totient for a prime). More generally, for any modulus m:
where φ(m) is Euler's totient function.
Euler's Totient for a Prime
For a prime p:
For a prime power:
The Algorithm
To evaluate a tower a₁^(a₂^(a₃^(...^aₙ))) mod m:
- If the tower has one element, return
a₁ mod m - Compute the exponent: recursively evaluate the rest of the tower mod
φ(m) - Return
a₁^(exponent) mod musing modular exponentiation
The recursion terminates because applying Euler's totient repeatedly eventually reaches 1.
Pseudocode
Worked Example
Evaluate 3^(4^5) mod 7:
Step 1: We need 3^(4^5) mod 7. Since 7 is prime, φ(7) = 6.
Step 2: Reduce the exponent: compute 4^5 mod 6.
4^5 = 10241024 mod 6 = 4
Step 3: Compute 3^4 mod 7.
3^4 = 8181 mod 7 = 4
Result: 3^(4^5) ≡ 4 (mod 7)
Python Implementation
C++ Implementation
Edge Cases
- Base is 0:
0^(anything > 0) = 0, but0^0 = 1by convention. - Modulus is 1: Any number mod 1 is 0.
- Base and modulus share factors: When
gcd(a, m) > 1, Euler's theorem does not directly apply. For the general case, use the lifting-the-exponent lemma or handle small exponents explicitly. - Very deep towers: The recursion depth equals the tower height. Since
φapplied repeatedly reaches 1 quickly (in O(log m) steps), the recursion terminates even for very tall towers.
Common Pitfalls
- Evaluating left to right: Power towers are always evaluated right to left (top down).
2^3^4means2^(3^4) = 2^81, not(2^3)^4 = 8^4 = 4096. - Forgetting the totient reduction: Without reducing the exponent mod
φ(m)at each level, intermediate values overflow any integer type. - Not handling
gcd(base, mod) > 1: The simple Euler approach assumes coprimality. For competitive programming, check if additional handling is needed.
Summary
- Use Euler's theorem to reduce exponents:
a^e mod m = a^(e mod φ(m)) mod m - Apply recursively: compute each level's exponent mod the totient of the current modulus
- The recursion terminates quickly because repeated totient application reaches 1 in O(log m) steps
- Works efficiently even for towers with billions of levels

