In the event that gcd(a,m) = 1, you can reduce b mod phi(m), for example because and and .

Often for a powermod calculation it's fast enough to compute by squaring while considering the exponent in binary. I explain it here (post #7).

http://www.mathhelpforum.com/math-he...tml#post508102

You might also like to compare with this Wikipedia article, which I found a bit hard to follow the last time I read it.

Modular exponentiation - Wikipedia, the free encyclopedia

For power towers, see this example (involving both totient and CRT - Chinese Remainder Theorem)

http://www.mathhelpforum.com/math-he...on-150486.html