// Fibonacci Series and Factorial Code // Jon F. // Last Modified: 11/1/2013 // needed libraries/modules #include #include using namespace std; // factorial as a loop long int factorial_loop(long int number) { // keep track of the answer long int answer = 1; // generate a vector with space for a numerical range of 2 -> n + 1 // range is 0 based from 0 -> number - 1 // and pads the vector with zeroes vector range((number + 1) - 2, 0); // generate an object to iterate over the vector vector::iterator in_range; // for all items in the vector for (auto in_range = range.begin(); in_range != range.end(); in_range++) { // get the current index of the iterator as a number long int current_index = in_range - range.begin(); // set the vector item at that index to the start of the first item // plus the index of that item in the current vector // (skips the first element and creates a list of 2 -> number) *in_range = (answer + 1) + current_index; } // for i in range vector multiply the answer by i for (auto &i : range) answer *= i; // return the answer return answer; } // recursive factorial long int factorial (long int number) { // factorial returns 1, else higher number multiplied // by the number below it if (number == 1) return 1; else return number * factorial(number - 1); } // recursive fibonacci long int fibonacci (long int number) { // fibonacci returns 0, 1, or the last two values added if (number == 0) return 0; else if (number == 1) return 1; else return fibonacci(number - 1) + fibonacci(number - 2); } // driver int main(int argc, const char * argv[]) { // factorial driver cout << "12 Factorial: " << endl; cout << "Loop: " << factorial_loop(12) << endl; cout << "Recursion: " << factorial(12) << endl << endl; // fibonacci driver cout << "12th Fibonacci Number: " << endl << fibonacci(12) << endl; }