I have two solutions for Project Euler question 2, namely find the sum of all even Fibonacci numbers less than 4 million.
Solution one (which takes an average of 11,000 nanoSeconds):
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);
}
and solution two(which takes an average of 14,000 nanoseconds):
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);
}
Why is solution two taking longer when I am performing way fewer iterations inside the while loop and and also do not have an if statement?
Can this be done more efficiently?
Running your algorithm only once is a highly unreliable way of evaluating its performance, particularly when the times are on the order of 10ns. Your second method is, indeed, faster. I rewrote your code to iterate each algorithm 100 times and got quite different results from you.
Code:
Results (typical):
Note that in the second algorithm, I changed
(4*prevTerm)with(prevTerm << 2), which is slightly faster. This improved the time by about 5%. There’s still a lot of overhead in each test: a function call and assigning the result to a local variable. However, by iterating you aren’t down in the noise in your calls toSystem.nanoTime().Note that your first code was also using a
doubleforUPPER_BOUND, which slows it down a bit. My code tried to make the tests as parallel as possible.