A fibonacci series is a series of numbers that the next number is found by adding the two immediate preceded numbers of it. For example : 0, 1, 1, 2, 3, 5, 8, 13, 21 . . In this article, we are going to write a program to print first N numbers in fibonacci series. See below example.
import java.util.Scanner; class Fibonacci{ public static void main(String args[]) { System.out.println("Please Enter Number: "); Scanner read = new Scanner(System.in); int count = read.nextInt(); int a1=0 , a2=1 , a3 ; System.out.print(a1+" "+a2); //prints 0 and 1 for(int i=2;i < count;i++) { a3=a1+a2; System.out.print( " "+a3); a1=a2; a2=a3; } } }
See below example to find Nth fibonacci number using mathematical formula. To find Nth fibonacci number mathematical formula is :
(X^n - (1 - X)^n)/√5 . where X = (1-√5 )/2
public class NthFibonacci{ public static void main(String as[]) { int number =20; double a = (1+Math.sqrt(5))/2; double b = (1-Math.sqrt(5))/2; double result = ( Math.pow(a,number)-Math.pow(b,number))/Math.sqrt(5); System.out.println(number +" th febinocci number is : "+(int)result; } }
Due to int size restriction in java , we can find upto 47th fibonacci number only.