The Fibonacci Sequence
The Fibonacci Sequence is the series of numbers that begin with:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
The next number is the sequence is found by adding the two numbers before it.
So the next numer in the sequence would be (55 + 34) = 89.
The Fibonacci Sequeces has a recursive definition such that the n'th Fibonocci number
f(n) = f(n - 1) + f(n - 2)
A method to find the n'th Fibonacci number is provided below; the main program prompts the
user for a positive number of Finbonacci numbers to print out.
Some variation may exist as to what the first number in the sequence should be, here is who this program will define the sequence:
- f(0) = 0, there really isn't a 0'th of anything when you think about it
- f(1) = 1
- f(2) = 1, either by definition of f(1) + f(0)
- f(3) = f(2) + f(1) = 2
- f(n) = f(n - 1) + f(n - 2)
|
public int fib(int n) {
if (n < 0) return -1; // n is not valid
if (n == 0) return(0);
if (n == 1) return(1);
if (n == 2) return(1);
if (n > 2) return fib(n - 2) + fib(n - 1);
return -1; // no way to get here
}
|
|
getInteger was called from the main program to get the number of Fibonacci numbers to print, and then called fibwas called for each value 1..number specified
Here is a sample program run :
|