I have coded a program which calculates Fibonacci Series in C++. Here's the code below:
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << endl;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
cout << endl;
return 0;
}
When I give input n = 100
, the list grows. And there appears some negative number.
I know it happens because of the data type value limit. But my question is why some of the are negative and some has positive value.
Like
-285007387, -945834654, -1230842041, 2118290601, 887448560, -1289228135, -401779575, -1691007710,
this is an example from the middle somewhere in the output.
Enter the number of terms: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, -1323752223, 512559680, -811192543, -298632863, -1109825406, -1408458269, 1776683621, 368225352, 2144908973, -1781832971, 363076002, -1418756969, -1055680967, 1820529360, 764848393, -1709589543, -944741150, 1640636603, 695895453, -1958435240, -1262539787, 1073992269, -188547518, 885444751, 696897233, 1582341984, -2015728079, -433386095, 1845853122, 1412467027, -1036647147, 375819880, -660827267, -285007387, -945834654, -1230842041, 2118290601, 887448560, -1289228135, -401779575, -1691007710, -2092787285, 511172301, -1581614984, -1070442683, 1642909629, 572466946, -2079590721, -1507123775, 708252800, -798870975, -90618175, -889489150,
Process finished with exit code 0
The appearance of both positive and negative numbers in your Fibonacci series is due to integer overflow.
When an integer overflows, its value wraps around. In the case of signed integers, which typically use two's complement representation, when the value exceeds the maximum positive value representable by the data type, it "wraps around" to the most negative value and continues decreasing. This explains why you're seeing negative values after reaching large positive ones.
For example, with a 32-bit signed integer:
That's why in your Fibonacci series, after reaching large positive numbers that caused overflow, you start seeing negative values, and the sequence continues with alternating positive and negative numbers as the overflow wraps around.