这是我的代码,已经一小时了,但还没有返回值,有什么问题吗?
import java.math.BigInteger;
public class PROJECTV1 {
public static void main(String[] args) {
BigInteger bResult = bigFunctionExample_2();
System.out.println(" => result_got:" + bResult);
System.out.println(); //newline
}// end_main
public static BigInteger bigFunctionExample_2() {
BigInteger bSum = BigInteger.ZERO;
BigInteger bTmp;
String sSum;
// BigInteger bResult =0;
for (int i = 1; ; i++) {
bTmp = BigInteger.valueOf(i);
bTmp = bTmp.pow(2); // i^2
bSum = bSum.add(bTmp); // sum = i^2+ (i-1)^2 + ....
sSum = bSum.toString();
if (sSum.length() > 30) {
System.out.println("i=" + i + " bSum =" + bSum);
break;
}
}//end_for
return bSum; // result
}
// end_bigFunctionExample_2
}
最佳答案
要打破该循环,它必须达到 10^30 ~= 2^100
。前 n 个自然数的平方和约等于 n^3。因此,大约当 i
变为 10^10 ~= 2^33
时,循环将中断。我猜 int i
是 32 位的,所以你可能会溢出该整数,我没有做精确的数学计算,但很有可能。
如果您选择 64 位变量(long
?),其上限约为 10^19
,您可能有机会 会没事的。
编辑:这是来自 WolframAlpha 的精确数学计算.
关于JAVA运行时间过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114007/