// =========================================================================== // Week 15: Algorithms // =========================================================================== // p. 9 double max (double array[], int len) { if (len == 1) // stopping condition return array[0]; else { // recursive call double subMax = max (array, len - 1); if (array[len - 1] > subMax) return array[len - 1]; else return subMax; } } // p. 10 int factorial (int n) { if (n == 1) // stopping condition return 1; else // recursive call return factorial (n - 1) * n; } // p. 13 int fib (int n) { if (n == 1) return 1; else if (n == 2) return 1; else // two recursive calls return (fib (n-1) + fib (n-2)); } // p. 15 double fibRepetitive (int n) { if (n == 1) return 1; else if (n == 2) return 1; double* fib = new double[n]; fib[0] = 1; fib[1] = 1; for (int i = 2; i < n; i++) fib[i] = fib[i - 1] + fib[i - 2]; double result = fib[n - 1]; delete[] fib; return result; } // p. 16 int main () // , , { int n = 0; cin >> n; time_t stTime = 0, endTime = 0; double duration = 0; stTime = clock(); cout << setprecision(100) << fibRepetitive(n) << endl; // algorithm 1 endTime = clock(); duration = static_cast(endTime - stTime) / CLK_TCK; cout << "seconds for algorithm 1: " << setprecision(5) << duration << endl; stTime = clock(); cout << setprecision(100) << fib(n) << endl; // algorithm 2 endTime = clock(); duration = static_cast(endTime - stTime) / CLK_TCK; cout << "seconds for algorithm 2: " << setprecision(5) << duration << endl; return 0; } // p. 18 #include using namespace std; void hanoi (char from, char via, char to, int disc) { if (disc == 1) cout << "From " << from << " to " << to << endl; else { hanoi (from, to, via, disc - 1); cout << "From " << from << " to " << to << endl; hanoi (via, from, to, disc - 1); } } int main () { int disc = 0; // number of discs cin >> disc; char a = 'A', b = 'B', c = 'C'; hanoi (a, b, c, disc); return 0; }