Fibonacci Sequence

2

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.

    
asked by anonymous 06.05.2017 / 21:31

1 answer

8

The algorithm does not do what is in the statement. It does not prompt you to create array . Okay, it's a form, but confusing and not optimized. It stops when the sum reaches 100000, this is never verified. It does not say how many interactions it needs to be made.

class HelloWorld {
    public static void main(String[] args) {
        int termo1 = 1;
        int termo2 = 2;
        int soma = 0;
        while (termo2 < 100000) {
            int novoTermo = termo1 + termo2;
            if (novoTermo % 2 == 0) {
                soma += novoTermo;
            }
            termo1 = termo2;
            termo2 = novoTermo;
        }
        System.out.println(soma);
    }
}

See running on ideone . And at Coding Ground . Also I put it in GitHub for future reference .

    
06.05.2017 / 21:59