/* computation of elements of the Fibonnaci sequence with and without dynamic prog. */ #include #include // for time int fibSeq1(int n) { if (n <= 1 ) return 1; else return fibSeq1 (n-1) + fibSeq1 (n-2); } int fibSeq2Helper (int n, int fibArr [ ]) { if (fibArr[n] != 0) return fibArr[n]; if (n <= 1) return fibArr[n] = 1; else return fibArr[n] = fibSeq2Helper (n-1, fibArr) + fibSeq2Helper (n-2, fibArr); } int fibSeq2 (int n) { //create NS INIRIliw local array for bookkeeping int arr [n+1]; for (int i = 0; i <= n; i++) arr[i] = 0; return fibSeq2Helper (n, arr); } int main ( ) { int reps = 100; // number of times call repeated to help timings printf ("timing of two functions to compute the nth Fib number\n"); printf (" (each function call repeated %d times)\n", reps); printf (" Approach 1 Approach 2\n"); printf (" n Fib[n] time Fib[n] time\n"); int n; int value; clock_t start_time, end_time; double elapsed_time; for (n = 1; n <= 45; n += 4) { printf ("%6d", n); // tim first approach start_time = clock (); for (int j = 0; j < reps; j++) value = fibSeq1 (n); end_time = clock(); elapsed_time = (end_time - start_time) / (double) CLOCKS_PER_SEC; printf ("%11d %6.1lf", value, elapsed_time); // time second approach start_time = clock (); for (int k = 0; k < reps; k++) value = fibSeq2 (n); end_time = clock(); elapsed_time = (end_time - start_time) / (double) CLOCKS_PER_SEC; printf ("%11d %6.1lf\n", value, elapsed_time); } }