Advertisement
cd62131

Fibonacci

Jul 23rd, 2014
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/time.h>
  3. #include <time.h>
  4. static unsigned long long fib(unsigned);
  5. static void initialize_memoize(void);
  6. static unsigned long long memoize_fib(unsigned);
  7. static unsigned long long accumulate_fib(unsigned);
  8. static unsigned long long accumulate_fib_sub(unsigned, unsigned long long, unsigned long long);
  9. static double diff_time(clock_t, clock_t);
  10. void puts_fib(unsigned long long (*)(unsigned), unsigned);
  11. int main(void);
  12. static unsigned long long fib(unsigned n) {
  13.   if (n < 2) return 1;
  14.   return fib(n - 1) + fib(n - 2);
  15. }
  16. static unsigned long long memo_fib[BUFSIZ];
  17. static void initialize_memoize(void) {
  18.   int i;
  19.   for (i = 0; i < BUFSIZ; i++)
  20.     memo_fib[i] = 0;
  21.   memo_fib[0] = 1;
  22.   memo_fib[1] = 1;
  23. }
  24. static unsigned long long memoize_fib(unsigned n) {
  25.   unsigned long long pre1, pre2;
  26.   if (n < 0) return 0;
  27.   if (memo_fib[n - 1])
  28.     pre1 = memo_fib[n - 1];
  29.   else
  30.     pre1 = memo_fib[n - 1] = memoize_fib(n - 1);
  31.   if (memo_fib[n - 2])
  32.     pre2 = memo_fib[n - 2];
  33.   else
  34.     pre2 = memo_fib[n - 2] = memoize_fib(n - 2);
  35.   return pre1 + pre2;
  36. }
  37. static unsigned long long accumulate_fib(unsigned n) {
  38.   return accumulate_fib_sub(n, 1, 1);
  39. }
  40. static unsigned long long accumulate_fib_sub(unsigned n, unsigned long long a, unsigned long long b) {
  41.   if (n < 1) return a;
  42.   return accumulate_fib_sub(n - 1, b, a + b);
  43. }
  44. static double diff_time(clock_t start, clock_t stop) {
  45.   return (double) (stop - start) / CLOCKS_PER_SEC;
  46. }
  47. void puts_fib(unsigned long long (*fib_func)(unsigned), unsigned n) {
  48.   clock_t start, stop;
  49.   unsigned long long f;
  50.   start = clock();
  51.   f = fib_func(n);
  52.   stop = clock();
  53.   printf("fib(%4d) = %lld\t[%.3lf sec.]\n", n, f, diff_time(start, stop));
  54. }
  55. int main(void) {
  56.   puts_fib(fib, 40);
  57.   initialize_memoize();
  58.   puts_fib(memoize_fib, BUFSIZ - 1);
  59.   puts_fib(accumulate_fib, BUFSIZ - 1);
  60.   return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement