0

I have this code for fibonacci sequence :

public class Fibonacci {
    private List<Integer> fibonacci;

    public void fillFibonacci(){
        fibonacci = new ArrayList<>();
        int n1 = 1 , n2 = 1 , n3;
        fibonacci.add(n1);
        fibonacci.add(n2);
        for(int i = 2 ; i < 4000 ; i ++){
            n3 = n1 + n2;
            fibonacci.add(n3);
            n1=n2;
            n2=n3;
        }
    }

    public void printFibonacci(){
        for(int i = 0 ; i < fibonacci.size() ; i ++){
            System.out.print(fibonacci.get(i) + " ");
            System.out.println(i);
        }
    }
}

this code show negative number what's wrong with it?

Laila Mattar
  • 361
  • 4
  • 19

2 Answers2

1

You cannot go up to index= 4000 in this loop, you have integer overflowed. Maximum you can go to is 49. Change the loop as such.

for(int i = 2 ; i < 49 ; i ++){
            n3 = n1 + n2;
            fibonacci.add(n3);
            n1=n2;
            n2=n3;
        }
berlin
  • 506
  • 4
  • 14
1

The 4000-th Fibonacci number has 836 digits. The java int type has 32-bits and can fit numbers up to 10 digits. After that it overflows and may go negative. If you want big numbers, change your code to use BigInteger.