- #1
Robben
- 166
- 2
Homework Statement
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.
Homework Equations
None
The Attempt at a Solution
I am not sure what is wrong with my code? The code produces a negative number when I type in 4000000 into the fib method parameter.
Java:
public static void fib(int k) {
int result = 0;
int[] array = new int[k];
array[0] = 1;
array[1] = 2;
for (int i = 2; i < k; i++) {
array[i] = array[i - 2] + array[i - 1];
}
for (int even: array) {
if (even % 2 == 0) {
result += even;
}
}
System.out.println(result);
}
Last edited: