Last active
December 16, 2017 17:20
-
-
Save jsbonso/1d3a7dc55b7cb369cb02a9a2913502a2 to your computer and use it in GitHub Desktop.
Java Fibonacci Sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculates the next fibonacci sequence. | |
* | |
* To properly implement a Fibonacci sequence, | |
* we need to know the Mathematical formula first, and that is: | |
* | |
* F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub> | |
* | |
* The above formula basically reads as this: | |
* The next sequence (Fn) is the sum of the | |
* 2 previous sequences (F<sub>n-1</sub> + F<sub>n-2</sub>) | |
* | |
* @param index of the Fibonacci sequence | |
* @author Jon Bonso | |
* @return | |
*/ | |
static int recursiveFibo(int num) { | |
if (num <= 1) return num; | |
// Implementation of the | |
// F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub> | |
else return recursiveFibo(num-1) + recursiveFibo(num-2); | |
} | |
/** | |
* Generate the Fibonacci Sequence | |
* @author Jon Bonso | |
* @param numOfSequences | |
*/ | |
static void generateFibonacciSequence(int numOfSequences) { | |
for(int i=0; i < numOfSequences; i++) { | |
System.out.println(recursiveFibo(i)); | |
} | |
} | |
public static void main( String[] args ){ | |
generateFibonacciSequence(10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: here's the Fibonacci sequence formula:
Fn = Fn-1 + Fn-2