For some reason when dealing with large numbers, the modulus operator doesnt give me the correct output, have a look at the code
double x = Math.pow(65,17) % 323
You can use int like this
int n = 65;
for (int i = 1; i < 17; i++)
n = n * 65 % 3233;
System.out.println(n);
or BigInteger like
System.out.println(BigInteger.valueOf(65).pow(17).mod(BigInteger.valueOf(3233)));
both print
2790
The result of Math.pow(65, 17)
cannot be represented exactly as a double
, and is getting rounded to the nearest number that can.
The pow(a, b) % c
operation is called "modular exponentiation". The Wikipedia page contains lots of ideas for how you might go about computing it.
Here is one possibility:
public static int powmod(int base, int exponent, int modulus) {
if (exponent < 0)
throw new IllegalArgumentException("exponent < 0");
int result = 1;
while (exponent > 0) {
if ((exponent & 1) != 0) {
result = (result * base) % modulus;
}
exponent >>>= 1;
base = (base * base) % modulus;
}
return result;
}