Tag Archives: fibonacci number

Fibonacci Series Java Program


“A fibonacci series is sequence of numbers, where each number is sum of the two preceding two numbers, Series initial two values are 1 , 1″

For Example : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144………

Fibonacci Series Program

Here is program to get Fibonacci series number on particular position and print series up to that point. In this program using recursion to generate Fibonacci numbers, Here put base condition to terminate recursion as when number reach to 1 or 2  and for rest of the case work recursively for current number and previous one and then add it.

import java.util.HashMap;
import java.util.Map;

public class FibonacciSeriesExample {

	private static Map series = new HashMap();

	public static void main(String[] args) {

		// Get the 12th fibonacci number from series
		System.out.println("Fibonacci 12 the position element :" + fibonacci(12));

		System.out.println("Print Complete Fibonacci Series :");
		printFibonacci(series);
	}

	public static int fibonacci(int fibIndex) {

		// set base element of fibonacci series
		if (fibIndex == 1 || fibIndex == 2) {
			series.put(1, 1);
			series.put(2, 1);
		}

		// execute fibonacci recursively until fibIndex reach to 1
		if (series.containsKey(fibIndex)) {
			return series.get(fibIndex);
		} else {
			int answer = fibonacci(fibIndex - 1) + fibonacci(fibIndex - 2);
			series.put(fibIndex, answer);
			return answer;
		}
	}

	public static void printFibonacci(Map series) {

		for (Map.Entry entry : series.entrySet()) {
			System.out.println(entry.getValue());
		}
	}
}

Output


Fabonnici 12 the position element :144
Print Complete Fabonni Series :
1
1
2
3
5
8
13
21
34
55
89
144

Advertisements