Fibonacci Numbers

In Mathematics the Fibonacci numbers are the following sequence of numbers
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55…..
the first two numbers are 0 and 1 the rest
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
Implementing Fibonacci in Java is easier done with recursion…. simply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. A recursive method consist of a “base case” and the “recursive call”.. here’s how to implement Fibonacci’s number with recursion

public static long fib(int n)
{
   if(n <= 2) return 1;
   else return fib(n - 1) + fib(n - 2);
}

but let’s take a look at how is done through linear programming.. that’s without recursion

public static long fib(int n)
{
if(n <= 2) return 1;
long fold = 1;
long fold2 = 1;
long fnew = 1;
for(int i = 3; i <= n; i++)
{
  fnew = fold + fold2;
  fold2 = fold;
  fold = fnew;
}
return fnew;
}
Share This!

Add a Comment

Your email address will not be published.

Sign up for our Newsletter

Download "Google Search Pro"

Enter your email and stay on top of things,

Subscribe!