由于某种原因,它总是返回值 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;
}