Fibonacci issue in Java

Asked

Viewed 860 times

1

I have a question and her resolution, which needs to be with while or do-while. But I did not understand the resolution, could someone explain to me? I will comment on the specific doubt of each line.

The Fibonacci sequence is a sequence of integer numbers in which, each subsequent term corresponds to the sum of the previous two. Being thus, draw up a algorithm reporting a sequence of Fibonacci which list the values started with 0 up to 2584.

Resolution:

public static void main(String[] args) {

    int x1=0;

    int x2=1;  // Por que tem que declarar duas variáveis?

    do{         System.out.print(x1 + " " );  // Por que o "  " depois do x1?

         x2= x2 +x1;   // Também não entendi por quê isso

         x1= x2-x1;    // Nem isso

    }while(x1<2584);}}  // E por que tem que ser do-while.
  • 1

    Unfortunately not every programmer calls the name that gives the variables, fields, classes and everything that can be named. This makes it more difficult to read the code. Oftentimes x, x1, a, b, aux are bad choices. This is best addressed in the book Clean Code, which I consider a reading indispensable for any developer nowadays.

  • 1

    @vnbrs great reading suggestion. The en translation has some gaffes but nothing that seriously compromises the quality of the content or reading

1 answer

4


Actually I think you need a course with the basics of logic and algorithm before you try to understand this.

I redid the code because it is very wrong. I put better names in the variables that helps understand

class Fibonacci {
    public static void main(String[] args) {
        int termo1 = 0;
        int termo2 = 1; //se são dois termos, precisa de duas várias para controlar
        do {
            System.out.print(termo1 + " "); //Está mandando imprimir um dos termos
            int temp = termo1 + termo2; //somando os dois últimos termos conforme o enunciado
            termo1 = termo2;  //fazendo o primeiro termo ter o valor do segundo
            termo2 = temp; //fazendo o segundo termo ter o valor somado dos últimos termos
        } while (termo1 <= 2584); //precisa de um laço para ficar repetindo até a condição
    }
}

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

"The Fibonacci sequence is a sequence of integer numbers in which each subsequent term corresponds to the sum of the previous two. Therefore, develop an algorithm that reports a Fibonacci sequence that lists the starting values with 0 to 2584.

The Fibonacci sequence is a sequence of integer numbers

If it is a sequence, we need a flow control structure that repeats each element of the sequence. And if it’s integer we need at least some integer data, it’s probably variable.

each subsequent term is the sum of the previous two

We already know how to get the subsequent terms. If you always need to add the two above we need to start with two of them, so we have at least two variables.

values starting from 0 to 2584

So the initial term is 0 and by definition Fibonacci the second is 1.

We also know that repetition must continue until the term 2584 is reached, so this is the condition that must be true for the loop of repetition to continue with the flow within it. One of the ways you can do this is do-while where the first time will always be executed the command blocks and after the first iteration it decides whether to continue or not. There are other ways to do it. Note that the condition was wrong, she disregarded the last number. The statement gives me the idea that it should be included.

Obviously every time we repeat a term we need to print, so we need to call the function that makes the impression. It would be interesting to give a space between the printed terms.

Again we go back to the explanation of how to get the new term and it’s the sum of the last two terms, so we created a variable to store that sum. Right now we have 3 terms, and we only need 2. In fact we can say that now the first term has the value of the second, and then we can say that the second has the value of the third that has just been generated, soon after we no longer need a third value. This is necessary to maintain the operation pattern of the repeat loop, will always add the 1st. and 2nd. terms.

Then repeat the new first term and start calculating everything again.

One might wonder if you need the temporary variable to calculate the subsequent term. And you need.

If you already played the sum of the two terms in the second, you would no longer have the previous value of the second term to play in the first term.

If I copied the second term to the first one, then the sum would be wrong because in practice I would be adding the second term with the first one that already has the value of the second one, I would have lost the value of the first one. At the bottom would be doubling the value and not making Fibonacci that is always go adding to the sequence.

With array you can simplify a little because in practice happens to have several variables, you do not lose the previous terms ever.

  • 1

    [@meta] I don’t know if it’s worth answering a question like "Describe me line by line what I did, because I don’t know how to visualize the algorithm." The idea is implementation of how to kill real problems, not cover college exercise.

  • Wow, thank you for that very dedicated answer! Actually my doubts are really about logic, because this question is the subject of Logic programming that I’m picking up in college, in the first semester. The professor indicated this site for when we had doubts, but from what I’m seeing, logic questions are not very welcome around here. Anyway, thank you for the explanation, Maniero.

  • 1

    @Spark idea of who? The question was not at its best, but it is fully pertinent to the site.

  • @Maniero fn = fn−1 + fn−2. The doubt was not the logic, it was the business rule. Well, we can remove the Java tag.

Browser other questions tagged

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