Large Fibonacci Numbers in Java


Given a number n, find n-th Fibonacci Number. Note that n may be large.


Input : 100
Output : 218922995834555169026

Input : 500
Output : 8616829160023845073278831216566478809594

Prerequisite : BigInteger Class in Java, Fibonacci numbers

Fibonacci of large number may contain more than 100 digits, it can be easily handled by BigInteger in Java. BigInteger class is used for mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.

// Java program to compute n-th Fibonacci
// number where n may be large.
import java.util.*;
import java.math.*;

public class Fibonacci
    // Returns n-th Fibonacci number
    static BigInteger fib(int n)
        BigInteger a = BigInteger.valueOf(0);
        BigInteger b = BigInteger.valueOf(1);
        BigInteger c = BigInteger.valueOf(1);
        for (int j=2 ; j<=n ; j++)
            c =  a.add(b);
            a = b;
            b = c;

        return (a);

    public static void main(String[] args)
        int n = 1000;
        System.out.println("Fibonacci of " + n +
            "th term" + " " +"is" +" " + fib(n));



Note that the above solution takes O(n) time, we can find n-th Fibonacci number in O(Log n) time. As an exercise, find n-th Fibonacci number for large n in O(Log n) time.

This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

1.2 Average Difficulty : 1.2/5.0
Based on 8 vote(s)

Writing code in comment? Please use, generate link and share the link here.