2

I'm writing algorithm for calculating $a^{a^{...^{a}}}$ mod $m$.

According to Euler's theorem, $a^k = a^{k\mod{\phi(m)}}$ mod $m$, if $a$ and $m$ are relatively primes. If $m = \prod_{i=0}^n p_i^{\alpha_i}$, where $p_i$ is prime, then $\phi(m) = \prod_{i=0}^n p_{i}^{\alpha_i - 1}*(p_i - 1)$. From the formula above, we can see, that applying $\phi$ to $\phi(\phi(...))$, at certain moment, we get power of 2 and after several steps - we get 1. It's gives us idea how to reduce expression $a^{a^{...^{a}}}$ mod $m$, if we know, that $a$ and all totients will be coprime, because there is no need to go further, if we got $\phi(\phi(...(m))) = 1$.

But if $a$ and $m$ are not coprime or at certain step $a$ and $\phi(\phi(...(m)))$ are not coprime, this method stop working. Bypass of this problem could be using of Chinese remainder theorem at step, when modulus and exponent base are not coprime. However, if $m$ has big prime factors, probably, there will be a lot of steps, when a is not coprime to modulus.

Question is, are there any other ways to compute expression above efficiently (modulus is not bigger than 10^7) ?

Bill Dubuque
  • 272,048

0 Answers0