Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/time.h>
- #include <time.h>
- static unsigned long long fib(unsigned);
- static void initialize_memoize(void);
- static unsigned long long memoize_fib(unsigned);
- static unsigned long long accumulate_fib(unsigned);
- static unsigned long long accumulate_fib_sub(unsigned, unsigned long long, unsigned long long);
- static double diff_time(clock_t, clock_t);
- void puts_fib(unsigned long long (*)(unsigned), unsigned);
- int main(void);
- static unsigned long long fib(unsigned n) {
- if (n < 2) return 1;
- return fib(n - 1) + fib(n - 2);
- }
- static unsigned long long memo_fib[BUFSIZ];
- static void initialize_memoize(void) {
- int i;
- for (i = 0; i < BUFSIZ; i++)
- memo_fib[i] = 0;
- memo_fib[0] = 1;
- memo_fib[1] = 1;
- }
- static unsigned long long memoize_fib(unsigned n) {
- unsigned long long pre1, pre2;
- if (n < 0) return 0;
- if (memo_fib[n - 1])
- pre1 = memo_fib[n - 1];
- else
- pre1 = memo_fib[n - 1] = memoize_fib(n - 1);
- if (memo_fib[n - 2])
- pre2 = memo_fib[n - 2];
- else
- pre2 = memo_fib[n - 2] = memoize_fib(n - 2);
- return pre1 + pre2;
- }
- static unsigned long long accumulate_fib(unsigned n) {
- return accumulate_fib_sub(n, 1, 1);
- }
- static unsigned long long accumulate_fib_sub(unsigned n, unsigned long long a, unsigned long long b) {
- if (n < 1) return a;
- return accumulate_fib_sub(n - 1, b, a + b);
- }
- static double diff_time(clock_t start, clock_t stop) {
- return (double) (stop - start) / CLOCKS_PER_SEC;
- }
- void puts_fib(unsigned long long (*fib_func)(unsigned), unsigned n) {
- clock_t start, stop;
- unsigned long long f;
- start = clock();
- f = fib_func(n);
- stop = clock();
- printf("fib(%4d) = %lld\t[%.3lf sec.]\n", n, f, diff_time(start, stop));
- }
- int main(void) {
- puts_fib(fib, 40);
- initialize_memoize();
- puts_fib(memoize_fib, BUFSIZ - 1);
- puts_fib(accumulate_fib, BUFSIZ - 1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement