Last active
February 1, 2022 10:46
-
-
Save isaacadariku/4d0093156501c1da3eee98e9a6c1e6a8 to your computer and use it in GitHub Desktop.
Dynamic programming for fibonacci
This file contains 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
void main() { | |
int i = 150; | |
final fib = fibonacciWithDynamicProgramming(); | |
print('fibonacciWithDynamicProgramming($i) = ${fib(i)}'); | |
print('fibonacci($i) = ${fibonacci(i)}'); //Uncomment this to try large numbers | |
} | |
/// Computes the nth Fibonacci number. | |
int fibonacci(int n) { | |
return n < 2 ? n : (fibonacci(n - 1) + fibonacci(n - 2)); | |
} | |
/// Computes the nth Fibonacci number with cache. | |
Function fibonacciWithDynamicProgramming() { | |
var cache = <int, dynamic>{}; | |
int fibonacci(int n) { | |
if (cache.containsKey(n)) { | |
return cache[n]; | |
} else if (n < 2) { | |
return n; | |
} else { | |
cache[n] = (fibonacci(n - 1) + fibonacci(n - 2)); | |
return cache[n]; | |
} | |
} | |
return fibonacci; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment