Project Euler #2 in Java 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 &lt; 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(&quot;Result: &quot; + sum + &quot;\nTime used for calculation in nanoseconds: &quot; + (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 &quot;bad code&quot; in the short solution?
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 &lt;= 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: " +
                (end - time));
    }
}


Output:


  Original code using pow:
  Result: 4613732
  Time used for calculation in nanoseconds: 9952  
  
  Using addition instead of pow:
  Result: 4613732
  Time used for calculation in nanoseconds: 934


(Note: both programs were modified to measure the end time before the println(), otherwise some of the string concatentation time was being counted).