[英]C# - Same Calculation Slower Using Int vs Long?
I've run into something really strange while working my way through some practice problems using dotnetfiddle . 在使用dotnetfiddle解决一些练习问题时,遇到了非常奇怪的事情 。 I have a program that applies a mathematical sequence (different calculations each step depending on whether the current step is even or odd):
我有一个应用数学序列的程序(每个步骤的不同计算取决于当前步骤是偶数还是奇数):
using System;
public class Program
{
public static void Main()
{
int ceiling = 1000000;
int maxMoves = 0;
int maxStart = 0;
int testNumber;
for(int i = 1; i <= ceiling; i++){
testNumber = i;
int moves = 1;
while(testNumber != 1){
if(testNumber % 2 == 0){
testNumber = testNumber / 2;
moves++;
} else {
testNumber = (3 * testNumber) + 1;
moves++;
}
}
if(moves > maxMoves){
maxMoves = moves;
maxStart = i;
}
}
Console.WriteLine(maxStart);
Console.WriteLine(maxMoves);
}
}
As written, the execution time limit gets exceeded. 如所写,超过了执行时间限制。 However, if I change the declaration of test number to a long instead of an int, the program runs:
但是,如果我将测试号的声明更改为long而不是int,程序将运行:
int maxMoves = 0;
int maxStart = 0;
**long** testNumber;
Why would making this change, which requires recasting i
from an int
to a long
each increment of the for loop (at testNumber = i
), be faster than leaving this as an int
? 为什么会做出这种改变,这就需要重铸
i
从int
到long
for循环(在每个增量testNumber = i
),会比把这个作为一个更快的int
? Is performing the mathematical operations faster on a long
value? 对
long
值进行数学运算是否更快?
The reason seems to be an overflow . 原因似乎是溢出 。 If you run that code enclosed in a
如果您运行包含在
checked
{
// your code
}
you get an OverflowException
when running with testNumber
as int
. 当将
testNumber
作为int
运行时,会收到OverflowException
。
The reason is that eventually 3*testNumber+1
exceeds the boundary of an int
. 原因是最终
3*testNumber+1
超出了int
的边界。 In an unchecked
context this does not throw an exception, but leads to negative values for testNumber
. 在
unchecked
上下文中,这不会引发异常,但是会导致testNumber
值为负 。
At this point your sequence (I think it's Collatz , right?) does not work anymore and the calculation takes (probably infinitly) longer, because you never reach 1
(or at least it takes you a whole lot more iterations to reach 1
). 在这一点上,您的序列(我认为是Collatz ,对吗?)不再起作用,并且计算(可能无限期地)花费了更长的时间,因为您从未达到
1
(或者至少需要更多的迭代才能达到1
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.