So I was just practicing coding a dynamic solution to the Fibonacci sequence which would return the n\'th Fibonacci number and I kept coming across a problem which I can\'t quit
Because of how C stores your int
(signed int) in memory, the most significant bit indicates a negative number. So you'll get negative number if you overflow it with large numbers.
Reference:
You need to change int
to unsigned int
or even better unsigned long long
. Your result is overflowing the maximum value of int
on your system. Because int
is signed, when the most significant bit gets set, it becomes a negative number. See the Stack Overflow question titled maximum value of int, and this Swarthmore College page on binary arithmatic for more information. If you're using Visual Studio, take a look at the Data Type Ranges article on MSDN.
In addition to switching to unsigned long long
, you should probably check for overflow errors such as this and throw an exception. A revised version of your code could look like this.
unsigned long long fib(int n) {
vector<unsigned long long> v;
v.push_back(1);
v.push_back(1);
for (int i = 2; i <= n; i++) {
if( v.at(i-1) > (std::numeric_limits<unsigned long long>::max() - v.at(i-2)) )
throw std::overflow_error("number too large to calculate");
v.push_back( v.at(i-1) + v.at(i-2) );
cout << v.at(i-1) << " + " << v.at(i-2) << " = " << (v.at(i-1) + v.at(i-2)) << endl;
}
return v.at(n);
}
You would also want to make sure the code calling your function can handle an exception by using a try... catch...
. Here's an example
try {
std::cout << "2000th number = " << fib(2000) << std::endl;
} catch( std::overflow_error& ex ) {
std::cerr << ex.what() << std::endl;
}