C# - for Loop Freezes at strange intervals

只谈情不闲聊 提交于 2019-12-02 07:21:35

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.

If goes into infinite loop in while (num != 1).

I bet that this version doesn't freeze, there's no reason it should do that.

The Collatz sequences before you hit 1 in the inner while loop are too short to lead to a noticeable delay, and if they would that should always happen at the same numbers.

If you add console output inside the loop then this may allocate memory, and the pauses you see could be due to garbage collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!