In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
My version is spelt differently so adjust the code accordingly if copying and pasting.
Chapter 5 // Exercise 11
Write a program that writes out the first so many values of the Fibonacci series, that is, the series that starts with 1 1 2 3 5 8 13 21 34. The next number of the series is the sum of the previous ones. Find the largest Fibonacci number that fits in an Int.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
int main()
try
{
vector<int> fibonacci = { 1,1 };
for (int i = 1; i < 100; ++i)
{
int sum = fibonacci[i] + fibonacci[i - 1];
fibonacci.push_back(sum);
}
for (int i = 0; i < fibonacci.size(); ++i)
{
cout << fibonacci[i] << '\n';
}
keep_window_open();
return 0;
}
catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;
}
This was pretty easy however I don't know if it's cheating by including the first 2 numbers. i starts at 1 on the first for loop because if it didn't we'd be going out of range on the vector because i[1] is equal to the 2nd value in Fibonacci.
The largest number (on my compiler) that would fit into an int was 1,863,311,903.
No comments:
Post a Comment