gpt4 book ai didi

JAVA运行时间过长

转载 作者:行者123 更新时间:2023-11-30 08:59:45 25 4
gpt4 key购买 nike

这是我的代码,已经一个小时了还没有返回值,有什么问题吗?

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 位的,所以你可能溢出了那个整数,我没有做精确的数学计算,但这是很有可能的。

如果您选择上限约为 10^19 的 64 位变量(long?),您可能有机会 会好的。

编辑:这是来自 WolframAlpha 的精确数学.

关于JAVA运行时间过长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com