我正在处理Project Euler的一些问题,但我偶然发现了一个问题。我不知道为什么这个算法不适用于2^1000。它适用于10^1和10^8范围内的数字(这些是我测试的数字),但它应该适用于所有可能的范围。
顺便说一下,2^1000是1.07*10^301。双精度的上限在10^308左右,所以这个数字仍然在范围内。
import java.lang.Math;
public class Euler15 {
public static void main(String[] args) {
int count = 0;
double res = Math.pow(2,1000);
for(int i = 301; i >= 0; i--){
if (res == 0){
break;
}
while (res >= Math.pow(10, i)){
res-= Math.pow(10, i);
System.out.println(res);
count++;
}
}
System.out.println(count);
}
}
2^1000对于普通数据类型来说太大了。使用BigInteger或字符串。
import java.math.BigInteger;
将输入作为BigInteger:
BigInteger n = BigInteger.valueOf(2);
现在加电至1000:
n = n.pow(1000);
现在,使用toString()
将其转换为字符串,然后将每个字符添加到结果中,将其更改为int
。应该这样做。