Skip to content

Instantly share code, notes, and snippets.

@Ephygtz
Created July 15, 2024 11:25
Show Gist options
  • Save Ephygtz/df798f783558909c066efc798c3e1fd8 to your computer and use it in GitHub Desktop.
Save Ephygtz/df798f783558909c066efc798c3e1fd8 to your computer and use it in GitHub Desktop.
Implementing the Fibonacci sequence with recursion and adding memoization to improve the runtime
public class FibonacciSequence {
//using recursion without memoization
public int calculateFibSequence(int n){
//1st check for negative numbers and throw an exception
if(n < 0){
throw new IllegalArgumentException("No fibonacci sequence for negative numbers");
} else if (n <=2){ //Base case
return n;
}
//create a variable to store fib calculation result
int result = calculateFibSequence(n-1) + calculateFibSequence(n-2);
//return fib calculation result
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment