Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Last active December 16, 2017 17:20
Show Gist options
  • Save jsbonso/1d3a7dc55b7cb369cb02a9a2913502a2 to your computer and use it in GitHub Desktop.
Save jsbonso/1d3a7dc55b7cb369cb02a9a2913502a2 to your computer and use it in GitHub Desktop.
Java Fibonacci Sequence
/**
* 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);
}
@jsbonso
Copy link
Author

jsbonso commented Oct 14, 2017

Note: here's the Fibonacci sequence formula:

Fn = Fn-1 + Fn-2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment