Fruloops
Fruloops

Reputation: 35

[Java]The bigger the numbers, the weirder the output of Fibonacci sequence

I have written a program that outputs the Fibonacci sequence and the program is working alright for small numbers. When I set the loop for 10 000th number of the sequence, the program goes super weird and starts outputting negative numbers alongside positive ones.

At first I though it was because I used int type for the numbers but then I changed it to long and the program still outputs the same things. I am quite new to java, so I guess either something is wrong with my program or I have missed a type that is larger than long and would not output a negative number.

Below is the code. Feel free to comment about anything else apart from just any mistakes, as I am fairly new to java so the code might look a bit amateurish:

public class Problem2{ //fibonacci sequence
    public static void main (String [] args ){
       long first = 1; 
       long second = 1;
       System.out.println(first);
       System.out.println(second);

       for ( int i = 1; i <= 100 ; i++){

        long third = first + second;            
        first = second;
        second = third;
        System.out.println(third);          
       }
    }
}

Outputs for the first 90 numbers are alright: 1 1 2 3 5 8 13 21 ... After that the the last 2 outputs are :

90th : 7540113804746346429

91st : -6246583658587674878

I sincerely apologize if this has been asked many times, I've searched around a little and didn't find much I could understand so I thought it might be best to ask.

Upvotes: 2

Views: 195

Answers (2)

kirti
kirti

Reputation: 4609

The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold

You can declare and initialize it as... For eg BigInteger bi1 = new BigInteger("12345678900123");

Change your program as

BigInteger first, second, third ;


first= new BigInteger("123");
    second= new BigInteger("50");

 for ( int i = 1; i <= 100 ; i++){

        third = first.add(second);           
        first = second;
        second = third;

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39477

This is called overflow. You should use the BigInteger class which is provided in Java. The Fibonacci sequence grows quite quickly so very soon its elements don't fit into int and also into long. So you get overflow and you start seeing negative numbers.

Upvotes: 4

Related Questions