pow(3,a)
produces huge numbers for big a
values, so it will very soon (starting from Math.pow(3, 87)
) produce values outside the range of double
("Infinity").
Also, your algorithm is entirely integer-based. You shouldn't use floating-point numbers for that calculation. Especially the loop index being double
has a "smell" (even if it works in your case).
I recommend using int
for the loop index and BigInteger
for a
:
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(7);
for (int i = 2; i < 100; i++) {
a = (BigInteger.valueOf(3).pow(a.intValue()).mod(BigInteger.valueOf(10).pow(i)));
System.out.println(a);
}
}
Note that pow
takes an int
for the exponent, so this solution has a limit, too.
In order to avoid that limit, you may want to write your own pow
function or use the combined modPow
operation. Since you know beforehand that the result of your exponentiation will be modulo a (relatively small) number, you can use the combined operation that uses that knowledge to execute the exponentiation much more efficiently.
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(7);
for (int i = 2; i < 100; i++) {
a = BigInteger.valueOf(3).modPow(a, BigInteger.valueOf(10).pow(i));
System.out.println(a);
}
}
This version doesn't have a limit apart from the available memory and the available processing time.