Yes, there is a faster method: modular exponentiation. http://en.wikipedia.org/wiki/Modular_exponentiation
Repeated multiplication (your algorithm) runs in exponential time, while modular exponentiation runs in polynomial time. It works like this:
Let's say, you want to compute A^B mod M. First, write B in binary:
B = bn,bn-1,...,b1,b0
This means, that
B = bn * 2^n + bn-1 * 2^(n-1) + ... + b1 * 2 + b0
Substituting this in the expression A^B:
A^B = A^(2^n)^bn * A^(2^(n-1))^bn-1 * ... * A^2^b1 * A^b0
A^(2^n) can be computed recursively:
A^(2^n) = (A^(2^(n-1)))^2
Now, the trick is, to use this identity to compute A^(2^i) for each i using repeated squaring modulo M. The usual identities of multiplication and exponentiation hold for modular arithmetics too, so this is perfectly legal. The full algorithm:
input: A,B,M
output: A^B mod M
result = 1
while(B != 0){
if(B is odd){
result = result * A mod M
}
B = B / 2
A = A * A mod M
}
return result