How would one do to calculate something like a^b mod m where 0<a,b,m<10000?

Is there an efficient algorithm do to this? I have heard (and think I understand it) that the Euler totient (phi)-function can be used, but I'm not quite sure how.

And if we go one step further, and want to know a^b^c mod m, 0 < a,b,c,m < 10000, can we use some kind of recursive formula?

Thanks!
Alex

In the event that gcd(a,m) = 1, you can reduce b mod phi(m), for example $\displaystyle 3^{101}\pmod{10}\equiv3^1\pmod{10}$ because $\displaystyle (3,10)=1$ and $\displaystyle \varphi(10)=4$ and $\displaystyle 101\equiv1\pmod{4}$.

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).