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:
. There is a VERY significant difference between the 4 millionth term in the Fibonacci Sequence and the highest term that does not exceed 4 million: so significant that using long or double can't possibly save you in the case of the former. Try adding a println to print the last term (array[k-1]) to see how quickly the series grows... compare for example k=10 ,20,30,40...can you imagine how large the 4 millionth term in the sequence must be?