- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我写的代码比我在网上找到的一些代码慢(超过最大时间),即使在线代码看起来更臃肿。
那么我进入了什么陷阱,我的代码看起来更干净但不知何故变慢了?
慢(我的):
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);
}
}
快速(在线):
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);
}
}
我在 .NET Fiddle 上测试过它, 其中my solution得到以下错误
Fatal Error: Execution time limit was exceeded
和 other solution打印正确的结果
Num: 837799 Count: 525
他们应该 1:1 做同样的事情。有人有想法吗?
最佳答案
造成差异的似乎是 int
与 long
。我想知道使用 int
的慢速代码是否存在溢出错误,导致它循环的时间更长,而使用 long
则不会溢出。具体来说,long sequence
(快速版本)与 int temp = i;
(慢速版本)。如果您使用 long temp = i;
,它就像快速代码一样工作。
果然,如果我们将代码包装在 checked
block 中,它会在 else temp = temp * 3 + 1;< 行抛出
OverflowException
/
关于c# - 自己的代码明显比别人慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657293/
通常当我请求线程转储时,系统性能不佳的症状很容易解释;也就是说,通常我会看到许多线程显然正在等待一个已被获取但未被另一个释放的监视器。 在这种情况下,我有很多线程在等待监视器 (0x965ad100)
C:\Users\shagy\Desktop\3RD YEAR 2ND SEMESTER\SPM\Newfolder\SPM-SMS>npm start npm ERR! path C:\Users\
我是一名优秀的程序员,十分优秀!