Thursday, 1 December 2016

Fibonacci Series in Java Using Recursion

Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series, we create a function to calculate Fibonacci number and then print those numbers on Java console.

Printing Fibonacci numbers in Java : Sample Code Example

Here is complete code example of printing Fibonacci Series in Java. Fibonacci series is calculated using both Iterative and recursive method and written in Java programming language. We have two functions in this example, fibonacci(int number)  and  fibonacci2(int number).The first one print Fibonacci series using recursion and the second one using for loop or iteration.

You can test this code on your computer as well. One you create your Java source file, just compile and run. It will ask you to enter the number till which you want to see the series. Once you enter then a number, it will print the Fibonacci series in the console.

Java Program to print Fibonacci Series

import java.util.Scanner;

/**
 * Java program to calculate and print Fibonacci number using both recursion
 * and Iteration.
 * Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2
 * first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
 *
 * @author Javin
 */
public class FibonacciCalculator {

    public static void main(String args[]) {
 
       //input to print Fibonacci series upto how many numbers
        System.out.println("Enter number upto which Fibonacci series to print: ");
        int number = new Scanner(System.in).nextInt();
   
        System.out.println("Fibonacci series upto " + number +" numbers : ");
        //printing Fibonacci series upto number
        for(int i=1; i<=number; i++){
            System.out.print(fibonacci2(i) +" ");
        }
 
    }

    /*
     * Java program for Fibonacci number using recursion.
     * This program uses tail recursion to calculate Fibonacci number for a given number
     * @return Fibonacci number
     */
    public static int fibonacci(int number){
        if(number == 1 || number == 2){
            return 1;
        }
   
        return fibonacci(number-1) + fibonacci(number -2); //tail recursion
    }

    /*
     * Java program to calculate Fibonacci number using loop or Iteration.
     * @return Fibonacci number
     */
    public static int fibonacci2(int number){
        if(number == 1 || number == 2){
            return 1;
        }
        int fibo1=1, fibo2=1, fibonacci=1;
        for(int i= 3; i<= number; i++){
         
            //Fibonacci number is sum of previous two Fibonacci number
            fibonacci = fibo1 + fibo2;          
            fibo1 = fibo2;
            fibo2 = fibonacci;
       
        }
        return fibonacci; //Fibonacci number
   
    }
}

Output:
Enter number upto which Fibonacci series to print:
12
Fibonacci series upto 12 numbers :
1 1 2 3 5 8 13 21 34 55 89 144

After asking to write simple Java program to print Fibonacci series and later asking for Fibonacci series using recursion, another important question interviewer ask is how do you improve your Fibonacci function both iterative and recursive one?

A technique called memoization can be used to drastically improve performance of method which calculates Fibonacci number. if you look at the method it repetitive creates same Fibonacci number e.g. In order to calculate 10th Fibonacci number function first create first 9 Fibonacci number, this could be very time consuming if you just increase the upper limit from 10 to 10K.

You can write code for Fibonacci series with memoization by just using a HashMap and checking if Fibonacci number for a corresponding number is already exits or not and calculate only if it doesn't exist.

Fibonacci Number in Java with Memoization

Here is the code example of printing Fibonacci number with memoization technique :

    /*
     * Java Program to calculate Fibonacci numbers with memorization
     * This is quite fast as compared to previous Fibonacci function
     * especially for calculating factorial of large numbers.
     */
    public static int improvedFibo(int number){
        Integer fibonacci = cache.get(number);
        if(fibonacci != null){
            return fibonacci; //fibonacci number from cache
        }
        //fibonacci number not in cache, calculating it
        fibonacci = fibonacci2(number);
     
        //putting fibonacci number in cache for future request
        cache.put(number, fibonacci);
        return fibonacci;
    }

Here is diagram of how Fibonacci series will look like when you draw :

Fibonacci Series in Java Using Recursion

Performance Comparison Fibonacci function with and without memoization

//comparison of performance of Fibonacci number with memoization
int number = 100000000;
long startTime = System.nanoTime();
int result = fibonacci2(number); //fibonacci number with memoization
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Time taken to calculate Fibonacci number upto 100M 
without memorization:" + elapsedTime);
      
startTime = System.nanoTime();
result = improvedFibo(number); //Fibonacci number with memoization
elapsedTime = System.nanoTime() - startTime;
System.out.println("Time taken to calculate Fibonacci number upto 100M 
with memorization:" + elapsedTime);

Output:
Time taken to calculate Fibonacci number upto 100M without memoization:149479613
Time taken to calculate Fibonacci number upto 100M with memoization:118972384