This post addresses the following :
– What is Fibonacci sequence
– Write a java program for Fibonacci sequence
– Fibonacci sequence in java
Fibonacci Series
Fibonacci series is a list of numbers, where next value in the series is the sum of previous two values.
In function notation, it is represented as :
f(n) = f(n-1) + f(n-2)
The only constraint here is n must be greater than zero.
The special initial values, f(0) and f(1) are defined as :
f(0) = 0 and f(1) =1
Therefore,
f(2) = f(1) +f(0) = 1
f(3) = f(2) + f(1) = 2
The Fibonacci numbers, f(n) for n = 0,1,2,.. are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
In this post, we will write a program to return the nth value of a Fibonacci sequence using recursion.
For recursive approach, the nth value in a Fibonacci sequence will be represented as :
Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
Fibonacci(1) = 1
Fibonacci(0) = 0
An Illegal Argument exception will be thrown for any n < 0
Here is the complete program :
package com.javatutorial; public class Fibonacci { public static void main(String[] args){ System.out.println("Fibonacci(10) = " + fibonacci(10)); } public static int fibonacci(int n){ if(n<0) throw new IllegalArgumentException("n should be non-negative"); else if(n==0) return 0; else if(n==1) return 1; else return (fibonacci(n-1) + fibonacci(n-2)); } }
Running this program will result in output :
Fibonacci(10) = 55
Algorithm to generate the fibonacci series
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CharPattern { public static void main(String[] args) { int n = 10; List<Integer> fibonacciList = fibonacciSeries(n); System.out.printf("Fibonacci sequence : %s", fibonacciList); } private static List<Integer> fibonacciSeries(int n) { List<Integer> fiboList = new ArrayList<Integer>(); if (n < 0) throw new IllegalArgumentException("n should not be less than zero"); else if (n == 0) return Arrays.asList(0); else if (n == 1) return Arrays.asList(0, 1); else { fiboList = new ArrayList<Integer>(); fiboList.add(0); fiboList.add(1); for (int i = 2; i < n; i++) { int elem1 = fiboList.get(i - 1); int elem2 = fiboList.get(i - 2); fiboList.add(elem1 + elem2); } } return fiboList; } }
Output :
Fibonacci sequence : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post
[…] Java program to calculate Fibonacci series :(Solution) […]
[…] How to form the Fibonacci series using recursion ? (Solution) […]