Created
July 15, 2024 11:25
-
-
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
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
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