Skip to content

Instantly share code, notes, and snippets.

@pyk
Last active August 29, 2015 14:25
Show Gist options
  • Save pyk/dc5528e960780c570f08 to your computer and use it in GitHub Desktop.
Save pyk/dc5528e960780c570f08 to your computer and use it in GitHub Desktop.
the comparison of naive recursion and dynamic programming to compute n-th fibonacci number
#include <stdio.h>
long long fib(long long n);
long long fibs[100];
long long
main()
{
long long i;
for(i = 1; i <= 50; i++)
printf("%lld ", fib(i));
}
/* fib: find the n-th fibonacci number */
long long
fib(long long n)
{
if(fibs[n]) return fibs[n];
if(n <= 2) {
fibs[n] = 1;
return fibs[n];
};
if(n > 2) {
fibs[n] = fib(n-1) + fib(n-2);
return fibs[n];
}
}
#include <stdio.h>
long long fib(long long n);
long long
main()
{
long long i;
for(i = 1; i <= 50; i++)
printf("%lld ", fib(i));
}
/* fib: find the n-th fibonacci number */
long long
fib(long long n)
{
if(n <= 2) return 1;
if(n > 2) return fib(n-1) + fib(n-2);
}
Compile
: ~/temp $ gcc -o fib-dc fib-dc.c
: ~/temp $ gcc -o fib fib.c
Using Dynamic Programming technique
: ~/temp $ time ./fib-dp
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811
514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 26791429
6 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025
real 0m0.001s
user 0m0.000s
sys 0m0.001s
Using naive-recursion technique
: ~/temp $ time ./fib
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811
514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 26791429
6 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025
real 3m21.680s
user 3m21.020s
sys 0m0.612s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment