Search code examples
javalong-integerbigintegerinteger-overflowbigint

Integer overflow for large a Fibonnaci sequence despite using Long primitive type and Big Integer


I'm making a program to print nth Fibonacci Number.

Method FIBBO(int n) uses a combination of long and BigInteger types to store the result of Fibonacci operations. The method is suppose to switch over to using BigInteger when it is deemed that prev+next>Long.MAX_VALUE using big_flag. However this program only works if i use Integer.MAX_VALUE in the 2nd loop.

When i use Long.MAX_VALUE, the 2nd loop of big_flag is never triggered now matter how large the value of n and i only get garbage values. I can't understand why my overflow logic is never activated when i use Long.MAX_VALUE.

import java.util.*;
import java.math.*;

public class fibbo_iteration{
    public static void main(String argss[])
    {
        BigInteger result;                      
        Scanner input=new Scanner(System.in);
        int n=0;                                
        System.out.println("Enter number of terms for fibbonacci sequence");
        n=input.nextInt();
        if(n<0){
            System.out.println("Fibbonaci sequence cannot be generated for the entered negative value");
            System.exit(1);
        }
        
        result=fibbo_iteration.FIBBO(n);        //call
        System.out.println(result.toString());  
    }
    static BigInteger FIBBO(int n)
    {
        // variables
        long sum=0L,prev=0L,next=1L;
        BigInteger big_prev=new BigInteger("0"),big_next=new BigInteger("0"),big_sum=new BigInteger("0");
        boolean big_flag=false;
    
            for(int i=0;i<n;i++){
                if(big_flag){
                    // System.out.println(big_sum.toString()); to use when printing a series upto n 
                    big_prev=big_next;
                    big_next=big_sum;
                    big_sum=big_prev.add(big_next);
                }
                else if(prev+next>Long.MAX_VALUE){   // ***The program works abolutely correct if i replace LONG.MAX_VALUE with Integer.MAX_Value***
                    big_prev=new BigInteger(String.valueOf(prev));
                    big_next=new BigInteger(String.valueOf(next));
                    big_sum=big_prev.add(big_next);
                    big_flag=true;  // this is supposed to signal the switch to BigInteger
                    System.out.println("Value exceeds Long");
                }   
                else{
                    if(i==1){   // this if block accomodates the eccentricity of starting the fibbonaci sequence  
                        sum=1L;
                        continue;
                    }   
                sum=prev+next;
                prev=next;
                next=sum;
                System.out.println(sum);
                }
            }
        return big_flag==true?big_sum:new BigInteger(String.valueOf(sum));
    }
}   

Solution

  • The max value of Long is really the maximum of the type. Any calculation above this is giving you... well results you apparently do not expect. A check of the kind prev+next>Long.MAX_VALUE is a nonsense. It will never be truthy.

    A bit of change that should make your program work is: prev > Long.MAX_VALUE - next

    If you want to understand in greater detail, you can use the comparison as I wrote it and debug, placing a breakpoint inside the if block. Try to see the value of prev+next. See how it goes negative. This is because you have reached values outside what long can store.