The standard trick for calculating a^p modulo m is to use a sequential square. The idea is to expand p into a binary file, say
p = e0 * 2^0 + e1 * 2^1 + ... + en * 2^n
where (e0,e1,...,en) are binary ( 0 or 1 ) and en = 1 . Then we use the laws of exponentials to obtain the following expansion for a^p
a^p = a^( e0 * 2^0 + e1 * 2^1 + ... + en * 2^n ) = a^(e0 * 2^0) * a^(e1 * 2^1) * ... * a^(en * 2^n) = (a^(2^0))^e0 * (a^(2^1))^e1 * ... * (a^(2^n))^en
Remember that each ei is either 0 or 1 , so they just tell you which numbers to take. So the only calculations you need are
a, a^2, a^4, a^8, ..., a^(2^n)
You can generate this sequence by squaring the previous word. Since you want to calculate the mod m answer, you need to do modular arithmetic first. This means that you want to calculate the following
A0 = a mod m Ai = (Ai)^2 mod m for i>1
Answer then
a^p mod m = A0^e0 + A1^e1 + ... + An^en
Therefore, the calculation takes the squares of log(p) and calls mod m .
I'm not sure if there is an analogue of factorials, but Wilson's theorem will be a good place to search. In addition, you must put the test m <= n , in this case n! mod m = 0 n! mod m = 0 .