I need to exercise on the Fibonacci sequence:
Each new term in the Fibonacci sequence is generated from the sum of the 2 previous terms. If we start with 1 and 2, the first ten numbers are: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Considering the terms of the Fibonacci sequence with values less than one hundred thousand, find the sum of all even numbers. Answer: 60696
And I'm almost there, see the code:
public static void main(String[] args) {
int termo1 = 1;
int termo2 = 2;
int termos[] = new int[10];
int soma = 0;
termos[0] = 1;
termos[1] = 2;
for (int i = 2; i < termos.length; i++) {
termos[i] = termos[i - 1] + termos[i - 2];
}
for (int termo : termos ) {
if (termo % 2 == 0) {
soma += (long) termo;
}
}
System.out.println(soma);
}
I am using arrays , and I am able to do with the first 10 terms of the sequence, the problem is that when I change the array size to 100000, it goes wrong, and negative number, as if the sum variable is not supported.