我运行了这段代码,它确实需要一段时间才能运行,但它似乎确实在进步(我确实增加了)。试试这个来确定 i 是否是素数:
public static bool IsPrime(long candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
return candidate == 2;
}
// Note:
// ... This version was changed to test the square.
// ... Original version tested against the square root.
// ... Also we exclude 1 at the very end.
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
我不能为此声称功劳。它来自http://www.dotnetperls.com/prime。
将一些 Console.WriteLines 添加到您的 main 方法中以使其进度:
static void Main(string[] args)
{
long number = 5;
for (long i = 1; i < 600851475143; i++)
{
if (IsPrime(i))
{
Console.WriteLine(i);
number = i;
}
}
}
这些算法还有其他资源:http:
//csharpinoneroom.blogspot.com/2008/03/find-prime-numer-at-fastest-speed.html
祝你好运!