Java 我正在研究斐波那契数,其中;";因为第n个数字是5-6位数字。如何减少执行所需的时间?
在这个特定的问题中,我要做的是找到斐波那契数,将它们平方,然后找到这些平方数的和。在长数据类型的范围限制之前,这是正常的 这是我到现在为止得到的。。。在注意到long的范围不能处理大的Fibonacci数之后,我切换到biginger,这确实起到了作用,但时间复杂度呈指数级增加。因为我需要保留大部分数字,所以我需要为数字创建一个数组来存储它们Java 我正在研究斐波那契数,其中;";因为第n个数字是5-6位数字。如何减少执行所需的时间?,java,Java,在这个特定的问题中,我要做的是找到斐波那契数,将它们平方,然后找到这些平方数的和。在长数据类型的范围限制之前,这是正常的 这是我到现在为止得到的。。。在注意到long的范围不能处理大的Fibonacci数之后,我切换到biginger,这确实起到了作用,但时间复杂度呈指数级增加。因为我需要保留大部分数字,所以我需要为数字创建一个数组来存储它们 import java.util.*; 导入java.math.*; 公共级斐波那契广场{ 私有静态BigInteger getFibonacciSumS
import java.util.*;
导入java.math.*;
公共级斐波那契广场{
私有静态BigInteger getFibonacciSumSquares(int n){
如果(nBigInteger的运行速度比java基元类型慢,那么在长范围内使用基元。
以下是我的代码和结果:
public class FibonacciSumSquares {
private static BigInteger getFibonacciSumSquares(int n) {
if (n <= 1)
return BigInteger.valueOf(n);
BigInteger sum = BigInteger.ZERO;
long last = 1, lastTwo = 1, current = 0;
BigInteger lastBigInteger = BigInteger.ONE;
BigInteger lastTwoBigInteger = BigInteger.ONE;
BigInteger currentBigInteger;
boolean isUsePrimary = true;
for (int i = 2; i <= n; i++) {
if (isUsePrimary) {
current = last + lastTwo;
current = current * current;
if (current > (last + lastTwo)) {
lastTwo = last;
last = current;
sum = sum.add(BigInteger.valueOf(current));
} else {
isUsePrimary = false;
lastTwoBigInteger = BigInteger.valueOf(lastTwo);
lastBigInteger = BigInteger.valueOf(last);
currentBigInteger = lastBigInteger.add(lastTwoBigInteger);
currentBigInteger = currentBigInteger.pow(2);
sum = sum.add(currentBigInteger);
}
} else {
currentBigInteger = lastBigInteger.add(lastTwoBigInteger);
currentBigInteger = currentBigInteger.pow(2);
sum = sum.add(currentBigInteger);
}
}
return sum;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(getFibonacciSumSquares(10000));
System.out.println("used time(ms): " + (System.currentTimeMillis() - start));
/**
* On: MacBook Pro (Retina, 15-inch, Mid 2014)
*
* n = 10000
* 811453295998950457153326378602357232029212
* used time(ms): 24
*
* n = 20000
* 1623556274380606238932066737816445867589212
* used time(ms): 32
*
* n = 999999
* 81209566945485034687670444066761210743605656
* used time(ms): 368
*/
}
公共类fibonaccisum{
私有静态BigInteger getFibonacciSumSquares(int n){
如果(n关于您的问题:当然,BigInteger允许您使用非常大的数字。但是,当然,任何对BigInteger对象的数字操作都比使用long原语类型要昂贵得多。因此:如果您确实想要性能和大数字,超出long的限制……那么您可以从long开始,一个当达到其限制时,例如切换到BigInteger。请注意,您正在通过用平方覆盖每个第I个值来阻止斐波那契数数组。您也可以放弃该数组,只保留最后2个值,但这将在空间复杂性方面有更大的改进。就我的文章的评论而言,谢谢试着这么做。@Ghostcata谢谢你指出了长范围的一个,我真的忘记了。第二个if语句的工作是处理长数据类型的范围,对吗?我对你的代码(从0到6000的随机类)做了一些压力测试,我想告诉你,除了值“2”之外,代码段工作得很好因为for循环忽略了它,所以我建议您在条件“iso”中的for循环中添加一个“=”符号,我建议您在条件“I”中的for循环中添加一个“=”符号