/* This function computes fibonacci numbers * param n index of the number to be computed * pre n>0 * ret the nth fibonacci number */ int fibonacciRecursive(int n) { /* FIXME you will write this function */ if (n == 0) return 0; else if (n == 1) return 1; else return (fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)); }
void TestFibonacciRecursive(CuTest *tc) { int expected[] = {0, 1, 1, 2, 3, 5}; int actual[arraylen(expected)]; int len = arraylen(expected); for (int i = 0; i < len; i++) { actual[i] = fibonacciRecursive(i); } CuAssertStrEquals(tc, IntArrayToString(expected, len), IntArrayToString(actual, len)); }
void TestFibonacciIterative(CuTest *tc) { int tests[] = {0,1,2,3,4,5,10,12}; int expected[arraylen(tests)]; int actual[arraylen(expected)]; int len = arraylen(tests); for (int i = 0; i < len; i++) { int num = tests[i]; expected[i] = fibonacciRecursive(num); actual[i] = fibonacciIterative(num); } CuAssertStrEquals(tc, IntArrayToString(expected, len), IntArrayToString(actual, len)); }
/* This function should call the fibonacci function a number of times, and write the * results to the file. * param filename name of the file to be opened * param maxFibonacciNumToCompute index of the max number to be computed * pre maxFibonacciNumToCompute>0 * post a file exists, with fibonacci numbers 1-Max written in it. */ void testRecursiveFibonacci(char* filename, int maxFibonacciNumToCompute) { /* FIXME you will write this function */ int nSum = 0, nNum = 0, i; FILE *recursive = fopen("recursive.txt", "w"); fprintf(recursive, "The numbers: \n"); fclose(recursive); for (i = 1; i <= maxFibonacciNumToCompute; i++) { nNum = fibonacciRecursive(i); recursive = fopen("recursive.txt", "a+"); fprintf(recursive, "%d\n", nNum); fclose(recursive); nSum += nNum; } recursive = fopen("recursive.txt", "a+"); fprintf(recursive, "\n The sum of %dth Fabonacii Number is : %d\n", maxFibonacciNumToCompute, nSum); fclose(recursive); }
int fibonacciRecursive(int n) { if (n <= 1) { return n; } return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); }