大概您的代码正在输出大量消息,这些消息看起来很混乱且毫无意义?有3个关键问题:
代码:
int a = Convert.ToInt32(number);
if (a % 2 != 0)
{
for (int i = 3 i < a; i += 2) // we can skip all the even numbers (minor optimization)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
goto escape; // we want to break out of this loop
}
// we know it isn't divisible by i or any primes smaller than i, but that doesn't mean it isn't divisible by something else bigger than i, so keep looping
}
// checked ALL numbers, must be Prime
Console.WriteLine("prime");
}
else
{
Console.WriteLine("not prime");
}
escape:
Console.ReadLine();
正如其他人所提到的,您只能通过每次评估平方根并替换此行来循环到 a 的平方根:
for (int i = 3 i < a; i += 2)
有了这个:
float sqrRoot = (Int)Math.Sqrt((float)a);
for (int i = 3 i <= sqrRoot; i += 2)
对其进行评估很重要,否则您的程序将运行得更慢,而不是更快,因为每次迭代都将涉及平方根运算。
如果您不喜欢goto语句(我喜欢 goto 语句),请发表评论,我会将其替换为突破布尔值(或参见 Dukeling 的最新答案)。