I’m trying to solve the 3n+1 problem using VS2010 c++,in small inputs it works well,but when it reaches 113383 it overflows.
Here is the problem link.
This is the code I’m using to solve this problem :
#include <iostream>
using namespace std;
int main(void) {
while (!cin.eof()) {
int i, j, maxCycle = 0, tmaxCycle = 0;
cin >> i >> j;
for (int x = i; x <= j; x++) {
int n = x;
tmaxCycle = 0;
while (n != 1) {
if ((float)(n/2) != (n/2.0)) {
n = 3*n + 1;
}
else {
n /= 2;
}
tmaxCycle += 1;
if (n < 0) {
int blah = 0; //just for the breakpoint
}
}
tmaxCycle += 1;
if (tmaxCycle > maxCycle) {
maxCycle = tmaxCycle;
}
}
cout << i << "\t" << j << "\t" << maxCycle << endl;
}
system("pause");
}
I made a breakpoint at line 15,and in this point values overflows
n=-1812855948
Use 64-bit unsigned integers. If those overflow, use a bignum library like the GNU Multiple Precision Library. Bignums give you unlimited precision and size.