我正在尝试使用 VS2010 c++ 解决 3n+1 问题,在小输入中它运行良好,但是当它达到 113383 时它会溢出。
这是 problem link .
这是我用来解决这个问题的代码:
#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");
}
我在第15行打了个断点,这个点值溢出了
n=-1812855948
最佳答案
使用 64 位无符号整数。如果这些溢出,请使用像 GNU Multiple Precision Library 这样的 bignum 库. Bignums 为您提供无限的精度和大小。
关于c++ - C++ VS2010中3n+1溢出的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12513512/