2
I need to do an exercise on the Fibonacci sequence:
Each new term in the Fibonacci sequence is generated from the sum of the previous 2 terms. If we start with 1 and 2, the first ten numbers will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Recital Fibonacci sequence terms below 100000, find the sum of all even numbers. Answer: 60696
and I’m almost there, look at 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’m using arrays, and I’m managing to do with the first 10 terms of the sequence, the problem is that when I change the size of the array for 100000, the sum of the terms goes wrong, and negative number, as if the sum variable does not support.
Try to make "
int soma = 0;
" was "long soma = 0;
"– Douglas
I did, gave -289570595282
– RickPariz
I switched the int to long and gave "7203226363417812526" when making the matrix like this "
long termos[] = new long[100000];
"; should have given "60696"?– Douglas
Yes, if you analyze the algorithm, I’m summing up all the even terms, so I would only need to change the type of the variables to give 60696
– RickPariz