Skip to content

Instantly share code, notes, and snippets.

@isaacadariku
Last active February 1, 2022 10:46
Show Gist options
  • Save isaacadariku/4d0093156501c1da3eee98e9a6c1e6a8 to your computer and use it in GitHub Desktop.
Save isaacadariku/4d0093156501c1da3eee98e9a6c1e6a8 to your computer and use it in GitHub Desktop.
Dynamic programming for fibonacci
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