我编写的代码比我在网上发现的一些代码更慢(超出最大时间),即使在线代码看起来更臃肿.
那么我陷入了什么陷阱,我的代码看起来更干净,但却以某种方式放慢了速度?
慢(我的):
using System;
public class Program
{
public static void Main()
{
int countMAX = 0;
int num = 0;
for (int i = 2; i <= 1000000; i++)
{
int count = 1;
int temp = i;
while (temp != 1)
{
if(temp % 2 == 0) temp /= 2;
else temp = temp * 3 + 1;
count++;
}
if(count > countMAX)
{
countMAX = count;
num = i;
}
}
Console.WriteLine("Number: " + num + " Hops: " +countMAX);
}
}
Run Code Online (Sandbox Code Playgroud)
快速(在线):
using System;
public class Program
{
public static void Main()
{
const int number = 1000000;
long sequenceLength = 0;
long startingNumber = 0;
long sequence;
for (int i = 2; i <= number; i++)
{
int length = 1;
sequence = i;
while (sequence != 1)
{
if ((sequence % 2) == 0)
{
sequence = sequence / 2;
}
else
{
sequence = sequence * 3 + 1;
}
length++;
}
//Check if sequence is the best solution
if (length > sequenceLength)
{
sequenceLength = length;
startingNumber = i;
}
}
Console.WriteLine("Num: " + startingNumber + " Count: " + sequenceLength);
}
}
Run Code Online (Sandbox Code Playgroud)
我在.NET Fiddle上测试了它,我的解决方案出现以下错误
致命错误:超出了执行时间限制
与其他解决方案打印出正确的结果
编号:837799总计:525
他们应该以1:1做同样的事情.有人有想法吗?
使其中的差别的事情似乎是intVS long.我想知道使用的慢代码int是否会遇到溢出错误,这会导致循环更长时间,并且使用long它会使其不溢出.具体而言,long sequence(快速版)vs int temp = i;(慢版).如果你使用long temp = i;它就像快速代码一样工作.
果然,如果我们将代码包装在一个checked块中,它会抛出一个OverflowException就行了else temp = temp * 3 + 1;
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |