Is this the most efficient way of doing it?
Sometimes the simplest solution is also the most efficient solution. I'm not sure why you decided to use Math.pow
and PHI
to compute something that can be easily (and more quickly) be computed with simple addition:
public class EvenFibonacciFinder {
private static final int MAX_NUM = 4_000_000;
public static void main(String[] args)
{
long time = System.nanoTime();
int f1 = 1;
int f2 = 2;
long sum = 0;
while (f2 <= MAX_NUM) {
int f3;
sum += f2;
// This skips three ahead in the sequence.
f3 = f1 + f2;
f1 = f2 + f3;
f2 = f1 + f3;
}
long end = System.nanoTime();
System.out.println("Result: " + sum +
"\nTime used for calculation in nanoseconds: " +
(System.nanoTime()end - time));
}
}
Output:
Original code using pow:
Result: 4613732
Time used for calculation in nanoseconds: 2966949952Using addition instead of pow:
Result: 4613732
Time used for calculation in nanoseconds: 45406934
(Note: both programs were modified to measure the end time before the println()
, otherwise some of the string concatentation time was being counted).