Related Articles

Related Articles

Large Fibonacci Numbers in Java
  • Difficulty Level : Basic
  • Last Updated : 20 Oct, 2020

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

Examples:

Input : 100
Output : 354224848179261915075

Input : 500
Output : 139423224561697880139724382870
         407283950070256587697307264108962948325571622
         863290691557658876222521294125 

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 the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.

JAVA

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to compute n-th Fibonacci
// number where n may be large.
import java.io.*;
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 (b);
    }
  
    public static void main(String[] args)
    {
        int n = 100;
        System.out.println("Fibonacci of " + n +
            "th term" + " " +"is" +" " + fib(n));
    }
}

chevron_right


Output

Fibonacci of 100th term is 354224848179261915075

Note that the above solution takes O(n) time, we can find the n-th Fibonacci number in O(log n) time. As an exercise, find the n-th Fibonacci number for large n in O(log n) time.
This article is contriBigInteger.valueOf (1);but by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :