Fibonacci of large number in java


Fibonacci numbers of Fibonacci series grows exponentially and can be very large for large numbers like 500 or 1000. To handle such number, long data type is not sufficient. BigInteger can handle large number easily. BigInteger is useful in scenarios where calculations results in data which is out of limit for available primitive data types. See the example below of getting Fibonacci number of 100 and 1000.

Example

 Live Demo

import java.math.BigInteger;
public class Tester {
   public static void main(String args[]) {
      System.out.println("Fibonacci of 100: ");
      System.out.println(fibonacci(100));
      System.out.println("Fibonacci of 1000: ");
      System.out.println(fibonacci(1000));
   }
   private static BigInteger fibonacci(int n) {
      BigInteger a = BigInteger.ZERO;
      BigInteger b = BigInteger.ONE;
      BigInteger c = BigInteger.ONE;
      for (int i=2 ; i<=n ; i++) {
         c = a.add(b);
         a = b;
         b = c;
      }
      return a;
   }
}

Output

Fibonacci of 100:
218922995834555169026
Fibonacci of 1000:
2686381002448535938614672720214292396761660931898695
2340123175997617981700247881689338369654483356564191
8278561614433563129766736422103503246348504103776803
67334151172899169723197082763985615764450078474174626

Updated on: 26-Jun-2020

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements