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 :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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

© 2015 – 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post

#

#