I am doing a small cryptography program and need a function to calculate power mod n
I wrote this method:
static int power(int x, int y, int p){
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or equal to p
while (y > 0) {
res = ((res*x) % p)+p % p;
y-=1;
}
return res;
}
But I have noticed it returns the wrong answer for certain cases. Example:
56295^779 mod 69997 should return 53580 but returns 20366 instead
43576^7116 mod 50087 should return 35712 but returns 40613 instead
It doesnt always return a wrong answer, so I am not sure why exactly this is happening. Any advice?
You are the victim of integer overflow.
res = ((res*x) % p)+p % p;
This line could overflow. res * x is not guaranteed to fit into a signed 32-bit integer (but does fit into a signed 64-bit integer).
Examples:
2147483647 * 2 = -2
1147483647 * 22 = -525163542
To prevent this from happening, you can make res a long
instead of int
, and then cast back to int
when returning from the function.
static int power(int x, int y, int p){
long res = 1; // Initialize as long to prevent overflow!
x = x % p;
while (y > 0) {
res = ((res*x) % p)+p % p; // No more overflow here!
y-=1;
}
return (int) res; // Cast result back to int
}