- #include <stdio.h>
- #include <time.h>
- long fib_iter(int n);
- long fib_cur(int n);
- static long COUNT = 0;
- int main(){
- clock_t c_start, c_end;
- int n;
- printf("Input a number: ");
- scanf("%d", &n);
- c_start = clock();
- long fib_iter_result = fib_iter(n);
- c_end = clock();
- printf("Iter: %ld, time elapsed: %ld\\n", fib_iter_result, (c_end - c_start) / CLOCKS_PER_SEC);
- c_start = clock();
- long fib_cur_result = fib_cur(n);
- c_end = clock();
- printf("Cur f(3): %ld\\n", COUNT);
- printf("Cur: %ld, time elapsed: %ld\\n", fib_cur_result, (c_end-c_start) / CLOCKS_PER_SEC);
- return 0;
- }
- long fib_cur(int n){
- if (n == 3)
- COUNT++;
- if (n <= 2)
- return 1;
- return fib_cur(n - 1) + fib_cur(n - 2);
- }
- long fib_iter(int n){
- long old = 1;
- long now = 1;
- long result;
- while (n > 2){
- result = old + now;
- old = now;
- now = result;
- n--;
- }
- return result;
- }
- //该片段来自于http://www.codesnippet.cn/detail/220720134719.html
来源: http://www.codesnippet.cn/detail/220720134719.html