Saturday, August 10, 2013

Java Program to Find Fibonacci Series of Given Number

Fibonacci? Consider requirement that I want to display Fibonacci series of number 10.If You remember maths in school, we used to find Fibonacci number using below :

Fibonacci is sum of previous two Fibonacci numbers fn= fn-1+ fn-2

Fibonacci of 10 will be 0 1 1 2 3 5 8 13 21 34  ex. 0 1 (0+1) (1st+2nd)...

Java Program to Find Fibonacci series of given Number :
package com.anuj.algorithms;

/**
 * 
 * @author Anuj
 *
 */
public class Fibonaci {

 /**
  * @param args
  */
 public static void main(String[] args) {
  int num=10;
  
  long[] fiboSeries = new long[num];
  fiboSeries[0] = 0;
  fiboSeries[1] = 1;
  
  //0 1 1 2 3 5 8 13 21 34
  for(int i=2;i<num;i++){
   fiboSeries[i] = fiboSeries[i-1] + fiboSeries[i-2];
  }
  
  for (long entry : fiboSeries) {
   System.out.print(entry + " ");
  }
 }
}

Output :
0 1 1 2 3 5 8 13 21 34

You may be Interested In :
  1. Check number is ArmStrong number or not using Java
  2. Check Number is Palindrom number or not using Java 
  3. How to Calculate Factorial of Number using Java with Recursion

No comments:

Post a Comment