Doubt about Fibonacci

1

I have a little doubt with my code to carry out my Fibonacci program since at the time of printing the values it gives me the number but in negative.

class doWhileTest{
    public static void main(String[] args) {
        int primertermino = -1;
        int segundotermino = 1;
        int incremento = 0;

        do{
            int fibo = primertermino + segundotermino;
            segundotermino = primertermino;
            primertermino = fibo;
            System.out.println(+fibo);
            incremento++;
        }
        while(incremento < 100);

        System.out.println("Se acabo");

    }
}
    
asked by Emilio Prior 14.08.2017 в 01:01
source

2 answers

1

The algorithm you're doing is something wrong, try this:

class doWhileTest{ 
public static void main(String[] args) { 
int f1=0,f2=-1,f3=1;
int incremento = 0;
    do{
        f1 = f2 + f3;
        f2 = f3;
        f3= f1;
        System.out.println(f1);
        incremento++;
    }while(incremento < 100);
    System.out.println("Se acabo");
    }
}

Keep in mind that your mistake is to declare a int fibo in each new cycle, which can cause the error you indicate, in addition to the algorithm being wrong when doing:

  

second term = prime term;
  first term = fibo;

you should do:

  

first term = second term;
  second term = fibo;

    
answered by 14.08.2017 / 01:13
source
0

The problem is that you are declaring variables type INT and you are only allowed up to a certain limit, testing with a variable type LONG gives you a greater capacity of numbers (It should be noted that in the fibonacci sequence very high numbers are reached) . I leave an algorithm that creates as a visual explanation

class doWhileTest
{
 public static void main(String[] args)
 {
  long x=1,y=0,suma=0,i=0;
  System.out.println(x);
  do
  {
   suma = x+y;
   System.out.println(suma);
   y=x;
   x=suma;
   i++;
  }while(i<100);
  System.out.println("Se acabo.");
 }
}'**
    
answered by 14.08.2017 в 03:48