The first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.

Here is the source code for generating the Fibonacci Series by using Recursion.

public class Fibonacci {

//Number of Fibonacci numbers to be shown

static int limit= 10;

static int count = 0;

public static void main(String[] args) {

System.out.print(0+” “);

fibo(0,1);

}

//Recursive Function

private static void fibo(int i, int j) {

count++;

System.out.print(j+" ");

if(count==limit)

return;

fibo(j,i+j);

}

}

This piece of code is ready to run. Copy this code into a file called Fibonacci.java, compile it and run. Here is the sample output of the above program. To generate the required number of numbers in the sequence, adjust the value of the integer variable “limit”.

0 1 1 2 3 5 8 13 21 34 55

## 1 comment:

Hi Cumar,

your example is short and nice, but it will fail on big numbers.

at first "int" is not big enough to hold big numbers and at second recursion will fail if you will have too much elelements in your stacktrace.

For example on "limit=100000" you will have StackTrace java.lang.StackOverflowError

here is my solution which use BigDecimal to store that huge numbers and don't use recursion

public class FibonacciNonRecursive {

static interface FibonacciListener {

void numberGenerated (Number number);

}

static class FibonacciPrintListener implements FibonacciListener {

private int currentId = 1;

private int logEveryNElement = 1000;

public void numberGenerated(Number number) {

if (currentId % logEveryNElement == 0){

System.out.print(number);

System.out.print(", ");

}

currentId++;

}

}

public static void main(String[] args) {

generateFibonachi (100000, new FibonacciPrintListener());

}

private static void generateFibonachi(int maxFibonachies, FibonacciListener fibonacciListener) {

BigDecimal first = new BigDecimal(0);

BigDecimal second = new BigDecimal(1);

fibonacciListener.numberGenerated(first);

for (int count = 1; count < maxFibonachies; count++){

BigDecimal next = first.add(second);

fibonacciListener.numberGenerated(next);

first = second;

second = next;

}

}

}

Post a Comment