Project Euler #2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Here is my solution:
public class EvenFibonacciFinder {
private static final double PHI = 1.618033989;
private static final double _PHI = -(PHI - 1);
private static final double SQRT_5 = Math.sqrt(5);
private static final int MAX_NUM = 4_000_000;
public static void main(String[] args) {
long time = System.nanoTime();
double max = MAX_NUM * SQRT_5;
long sum = 0;
for (int i = 3, result = (int) Math.round(2 * SQRT_5); result < max; result = (int) Math.round(Math.pow(PHI, i += 3) - Math.pow(_PHI, i))) {
sum += result;
}
sum = Math.round(sum / SQRT_5);
System.out.println("Result: " + sum + "\nTime used for calculation in nanoseconds: " + (System.nanoTime() - time));
}
}
Output:
Result: 4613732
Time used for calculation in nanoseconds: 60243
Questions:
- Is this the most efficient way of doing it?
- Is there any "bad code" in the short solution?
result = (int) Math.round(Math.pow(PHI, i += 3) - Math.pow(_PHI, i))
. Do you know if java specifies an evaluation order for the increment? I'm not sure which value ofi
is passed to the secondMath.pow
\$\endgroup\$