KatInterview

Modular Exponentiation Tower (Tetration mod M)

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationmathmodular arithmeticnumber theory

Last 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 n with gcd(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) provided x ≥ φ(n).
  • The recursion bottoms out quickly because φ(n) < n for n > 1, so φ applied repeatedly reaches 1 within O(log n) steps.

Constraints

  • 2 ≤ a ≤ 10
  • 0 ≤ h ≤ 100
  • 2 ≤ m ≤ 10^6
  • When h = 0, the tower equals 1 by convention, so the answer is 1 mod m.
  • When m = 1, the answer is always 0.
  • You may assume a ≥ 2, so the tower grows without bound for h ≥ 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.