I am wondering how to calculate x^y mod z. x and y are very large (can't fit in 64 bit integer) and z will fit 64 bit integer. And one thing don't give answers like x^y mod z is same as (x mod z)^y mod z.
Asked
Active
Viewed 4,347 times
-1
-
http://stackoverflow.com/questions/8496182/calculating-powa-b-mod-n – phuclv Jan 25 '15 at 17:18
2 Answers
3
Here is the standard method, in pseudo-code:
function powerMod(b, e, m)
x := 1
while e > 0
if e % 2 == 1
x := (b * x) % m
e := e - 1
else
b := (b * b) % m
e := e / 2
return x
The algorithm is known as exponentiation by squaring or the square and multiply method.

user448810
- 17,381
- 4
- 34
- 59
2
If you are using Java, then turn x, y, and z into BigInteger.
BigInteger xBI = new BigInteger(x);
BigInteger yBI = new BigInteger(y);
BigInteger zBI = new BigInteger(z);
BigInteger answer = xBI.modPow(yBI,zBI);

ProgrammersBlock
- 5,974
- 4
- 17
- 21