对于 Project Euler 问题 2,我有两个解决方案,即找到所有小于 400 万的偶数斐波那契数的总和。
解决方案一(平均需要 11,000 纳秒):
public class Solution {
static long startTime = System.nanoTime();
static final double UPPER_BOUND = 40e5;
static int sum = 2;
public static int generateFibNumber(int number1, int number2){
int fibNum = number1+ number2;
return fibNum;
}
public static void main( String args[] ) {
int i = 2;
int prevNum = 1;
while(i <= UPPER_BOUND) {
int fibNum = generateFibNumber(prevNum,i);
prevNum = i;
i = fibNum;
if (fibNum%2 == 0){
sum += fibNum;
}
}
long stopTime = System.nanoTime();
long time = stopTime - startTime;
System.out.println("Sum: " + sum);
System.out.println("Time: "+ time);
}
和解决方案二(平均需要 14,000 纳秒):
public class Solution2 {
static long startTime = System.nanoTime();
final static int UPPER_BOUND = 4_000_000;
static int penultimateTerm = 2;
static int prevTerm = 8;
static int currentTerm = 34;
static int sum = penultimateTerm+ prevTerm;
public static void main( String args[]) {
while (currentTerm <= UPPER_BOUND) {
sum+= currentTerm;
penultimateTerm = prevTerm;
prevTerm = currentTerm;
currentTerm = (4*prevTerm) + penultimateTerm;
}
long stopTime = System.nanoTime();
long time = stopTime - startTime;
System.out.println("Sum: " + sum);
System.out.println("Time: " + time);
}
当我在 while 循环中执行更少的迭代并且也没有 if 语句时,为什么解决方案二需要更长的时间?这可以更有效地完成吗?