Project Euler #2 Java

时间:2016-10-15 17:13:51

标签: java for-loop fibonacci

prompt:

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.

My Code:

public class EvenFibonaccinumbers {

    public static void main(String[] args) {
        long sum = 0;
        for (int i = 1; i < 4000000; i += (i - 1)) {
            if (i % 2 == 0) {
                sum += i;
            }
        }
        System.out.println("Sum: " + sum);
    }
}

ISSUE: Eclipse console remains blank

1 个答案:

答案 0 :(得分:1)

这是因为无限循环...

for (int i = 1; i < 4000000; i += (i - 1)) {
    // first iteration: i = 1
    // (i - 1) = (1 - 1) = 0: therefore i += 0
    // i always = 1
}