Long Overflow in Java program

I wrote a program to calculate the Fibonacci series I need to return the Last digit of Fibonacci as a result but when I check the results/ long overflow occurring from the 93rd Fibonacci number and I need to get the 239th Fibonacci numbers last digit help!

You can use BigInteger for that

Well, to get last digit of nth fibonacci number, you need not calculate nth fibonacci number. Let me tell you why!
You would find last digit of some number, say x, using modulo operator, like x % 10.
Now, Fibonacci series is defined by the recurrence relation, F_n = F_{n-1} + F_{n-2} , with F_0 = 0\ and\ F_1 = 1.
Modulo Operator is Distributive over Addition, which means, (a + b)%m = (a%m + b%m)%m;
Now, to calculate last digit of nth Fibonacci Number, you can simply use the property iteratively.
Code:

import java.util.*;
class Main {
    public static void main (String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int a = 0;
        int b = 1;
        int ans = -1;
        if(n==0)
            ans = 0;
        else if(n==1)
            ans = 1;
        n -= 1;
        while(n>0) {
            ans = (a + b)%10;
            a = b;
            b = ans;
            n -= 1;
        }
        System.out.println(ans);
    }
}
1 Like