c++ - C++ VS2010中3n+1溢出的解决方法

标签 c++ visual-studio-2010 overflow

我正在尝试使用 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/

相关文章:

visual-studio-2010 - Visual Studio 2010 - 尝试在文件中查找时禁用 "Find All"按钮

c# - 如何像 Access 一样使用 c# datagridview 更新数据库文件?

android - Webview iframe 溢出

c++ - c_str() 与 std::string - 这段小代码的真正区别是什么?

c++ - C++0x 中有哪些新的 Unicode 函数?

c++ - 如何使用 OpenCV 进行人脸识别?

asp.net - WCF 远程调试符号的位置

c++ - 在 C++/Qt 中绘制音频波形

javascript - 帧溢出可见?

css - 为什么 CSS 宽度为 :100% cause horizontal scrolling?