gpt4 book ai didi

c++ - 陷入无限循环? (可能是)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:11 25 4
gpt4 key购买 nike

我正在尝试完成欧拉计划 Problem 14在 C++ 中,老实说我被困住了。现在,当我运行问题时,它卡在了 So Far: the number with the highest count: 113370 with count of 155到目前为止:计数最高的数字,但是当我尝试将 i 值更改为超过 113371 时,它起作用了。这是怎么回事??

问题是:

The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain?

#include<stdio.h>
int main() {
int limit = 1000000;
int highNum, number, i;
int highCount = 0;
int count = 0;
for( number = 13; number <= 1000000; number++ )
{
i = number;
while( i != 1 ) {
if (( i % 2 ) != 0 ) {
i = ( i * 3 ) + 1;
count++;
}
else {
count++;
i /= 2;
}
}
count++;
printf( "So Far: the number with the highest count: %d with the count of %d\n",
number, count );
if( highCount < count ) {
highCount = count;
highNum = number;
}
count = 0;
//break;
}
printf( "The number with the highest count: %d with the count of %d\n",
highNum, highCount );
}

最佳答案

您遇到了整数溢出。像这样更新您的代码并自己查看:

if (( i % 2 ) != 0 ) {
int prevI = i;
i = ( i * 3 ) + 1;
if (i < prevI) {
printf("oops, i < prevI: %d\n", i);
return 0;
}
count++;
}

您应该将i 的类型更改为long longunsigned long long 以防止溢出。

(是的,缓存中间结果)

关于c++ - 陷入无限循环? (可能是),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26556692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com