Skip to content

Instantly share code, notes, and snippets.

@10MINT
Last active July 7, 2018 23:56
Show Gist options
  • Select an option

  • Save 10MINT/f987f2df4d25dea9192ee1736f015b47 to your computer and use it in GitHub Desktop.

Select an option

Save 10MINT/f987f2df4d25dea9192ee1736f015b47 to your computer and use it in GitHub Desktop.
Shows the differences between recursive and dynamic programming
int calls = 0;
int i = 35; //the fibonacci number to calculate
void main() {
Stopwatch _timer;
_timer = new Stopwatch()..start();
print('fibonacci($i) = ${recursiveFibonacci(i)} was calculated using the recursive approach. (time: ${_timer.elapsedMilliseconds} ms, calls: $calls)');
_timer.reset();
calls = 0;
print('fibonacci($i) = ${dynamicFibonacci(i)} was calculated using the dynamic approach. (time: ${_timer.elapsedMilliseconds} ms, calls: $calls)');
}
/// Computes the nth Fibonacci number with recursive calls.
int recursiveFibonacci(int n) {
calls++;
return n < 2 ? n : (recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2));
}
/// Computes the nth Fibonacci number with dynamic programming
int dynamicFibonacci(int n) {
calls++;
var f = [0, 1];
for (int k = 2; k <= n; k++) {
calls++;
f[k%2] = f[(k-1)%2] + f[(k-2)%2];
}
return f[n%2];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment