C# - for循环冻结在奇怪的时间间隔 [英] C# - for Loop Freezes at strange intervals
问题描述
我的工作问题14 上项目欧拉和我代码似乎在无缘无故随机间隔冻结。
I am working on Problem 14 on Project Euler, and my code seems to freeze at random intervals for no apparent reason.
static void Main()
{
int maxNum = 0;
int maxLength = 0;
for (int x = 2; x < 1000000; ++x)
{
int num = x;
int length = 0;
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
length++;
}
else
{
num = (3 * num) + 1;
length++;
}
}
if (length > maxLength)
{
maxLength = length;
maxNum = x;
}
}
Console.WriteLine(maxNum);
Console.ReadLine();
我每次运行它似乎并没有按照时间程序挂在数量是不同的任何一套模式。为什么它会挂这样的任何想法?先谢谢了。
The number that the program hangs at is different each time I run it and doesn't seem to follow any set patterns. Any ideas on why it would be hanging like this? Thanks in advance.
推荐答案
我以另一种方式解决了这个问题,通过缓存结果每一步,我已经找到你的问题。我怀疑你的程序一旦停止。结果
语句 NUM =(3 * NUM)+ 1
可能会溢出超过 Int32.MaxValue
,并导致一个负数和一个无限循环(?)。结果
在这种情况下,您可以通过使用解决问题长
为你的X。
I've solved it in another way, by caching the result for each step, and I've found your problem. I doubt your program ever stops.
The statement num = (3 * num) + 1
may overflow over Int32.MaxValue
and result in a negative number and an infinite loop(?).
In this case, you can solve the problem by using long
for your x.
这篇关于C# - for循环冻结在奇怪的时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!