Collatz序列算法不能正常工作

Collatz sequence algorithm not working right

本文关键字:工作 常工作 算法 不能 Collatz      更新时间:2023-10-16

由于某种原因,这总是返回值1。这样做的目的是找到循环次数最多的起始数(1-1,000,000)(直到j = 1)。j最终总是为1 (collatz理论),如果j是偶数,则将其除以2,如果是奇数,则乘以3并加1。

#include <iostream>
using namespace std;
int collatz() {
int counter = 0;
int holder = 0;
for (int i = 999999; i > 1; i--){           // loops 999,999 times
    for (int j = i; j != 1; counter++) {    // loops until j = 1, records amount of loops
        if (j % 2 == 0) {                   // if j is even, divide by 2, +1 to counter
            j = j / 2;
        } else {
            j = (j*3) + 1;                  // if j is odd, multiply by 3 and add 1, +1 to counter
        }
    }
    if (holder < counter){          // records highest number of loops
    holder = counter;
    counter = 0;
    } else {
    counter = 0;
    }

}
    return holder;
}
int main()
{
    cout << collatz << endl;
    return 0;
}

你不是调用你的函数,你是打印出函数指针(它被转换为booltrue(即1))

首先,使用unsigned intunsigned long long作为j的变量类型,以增加算术范围。

然后,在循环中,检查是否溢出。

 while (j!=1) {
    counter++;
    if (j % 2 == 0) {
        j >>= 1;
    } else {
        unsigned int j2 = j;
        j = (j*3) + 1;
        if (j2 > j) {
           return -1;  // or surround this with try/catch/throw exception
        }
   }
 }

对于int i;,计数器将在i==113383时溢出;
unsigned int i;在159487。