Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Program Fibonacci Sequence

Tags:

java

fibonacci

I am writing a "simple" program to determine the Nth number in the Fibonacci sequence. Ex: the 7th number in the sequence is: 13. I have finished writing the program, it works, but beginning at the 40th number it begins to delay, and takes longer, and longer. My program has to go to the 100th spot in the series.

How can I fix this so it doesn't take so long? This is very basic program, so I don't know all the fancy syntax codes.. my formula is:

if n =1 || n = 0
   return n;

else 
    return F(n-1) + F(n-2);

This works great until it goes past the 40th term. What other statement do I have to add to make it go quicker for higher numbers??

like image 511
Javadork Avatar asked Nov 25 '09 21:11

Javadork


People also ask

Is there a Fibonacci function in Java?

The Java Fibonacci recursion function takes an input number. Checks for 0, 1, 2 and returns 0, 1, 1 accordingly because Fibonacci sequence in Java starts with 0, 1, 1. When input n is >=3, The function will call itself recursively. The call is done two times.

How do you write a recursion Fibonacci sequence in Java?

Algorithm for Fibonacci Series using recursion in JavaIn the main() function we call the function fib() for the nth number. Then we set the base cases for the recursive call and return 0 and 1 , respectively, for the 0th and 1st index. We call fib(x) = fib( x-1 ) + fib( x-2 ) for all x > 2 .


1 Answers

The problem is that because you are using simple recursion, you re-evaluate F(n) multiple times, so your execution time is exponential.

There are two simple ways to fix this:

1) Cache values of F(n) when they are evaluated the first time. Check the cache first before evaluating F(n) to see if you have already calculated it for this n.

2) Use an iterative approach: Calculate F(1), F(2), F(3), etc... until you reach the number you need.

like image 172
Mark Byers Avatar answered Sep 27 '22 20:09

Mark Byers