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?