Considering that the input is specified as n -bit numbers with no explicit boundary for n , you should probably use BigInteger instead of double :
static BigInteger modExp(BigInteger base, BigInteger exponent, BigInteger m) { int trailing_zero_bits_count = exponent.getLowestSetBit(); if (trailing_zero_bits_count == -1) // exponent == 0 return BigInteger.ONE.mod(m); BigInteger z = modExp(base, exponent.shiftRight(1), m); // base**(exponent//2)% m BigInteger z_sq = z.pow(2).mod(m); // z**2 % m if (trailing_zero_bits_count != 0) // even return z_sq; return z_sq.multiply(base).mod(m); // z**2 * base % m }
It is worth noting that this code returns zero, not one for modExp(x, 0, 1) that is, if y == 0 , then the code does not return 1 as in the question condition is mistakenly indicated — if N == 1 , because 1 % 1 == 0 .
double? In my opinion, I mean integer operations ... - Harry