Java Interesting Problems

How to print Fibonacci Series Till 1000 ?

import java.math.BigInteger; 

public class FibonacciSeries
{
	public static void main(String[] args) {
	    int input = 100;
		BigInteger n1=BigInteger.valueOf(0),n2=BigInteger.valueOf(1),n3=BigInteger.valueOf(0);
		for(int i=2;i<=input;i++) {
			n3=n3.add(n1).add(n2);
			System.out.println(n3);
			n1=n2;
			n2=n3;
		}
	}
}

Learning from the above program:

  • You can not use int/Integer and also long/Long to store the value. Because maximum value of int(2147483647) and long(9223372036854775807). Both these values would be reached even before the first 100 fibonacci series values.
  • So BigInteger is one and only option for us to print the value of fibonacci series more than 100.
  • BigInteger size is int[] of 2147483647 [Integer.MAX_VALUE), so it can able to keep the big values in the form of array], so BigInteger can only be used as class, we dont have primitive data types for BigInteger like int/long.

Leave a Reply