Fibonacci sequence

Asked

Viewed 771 times

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;"

  • I did, gave -289570595282

  • I switched the int to long and gave "7203226363417812526" when making the matrix like this "long termos[] = new long[100000];"; should have given "60696"?

  • 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

1 answer

8


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

class Main {
    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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • class HelloWorld...

  • C# is already a disgrace because it requires class even in a simple thing, Java is worse because it requires the same name of the file, so it takes a lot of work to change in these online IDE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.