我实际上对我的问题有一个答案,但它不是并行化的,所以我对改进算法的方法感兴趣。无论如何,它可能对一些人有用。在C#中计算素数的最快方法?
int Until = 20000000;
BitArray PrimeBits = new BitArray(Until, true);
/*
* Sieve of Eratosthenes
* PrimeBits is a simple BitArray where all bit is an integer
* and we mark composite numbers as false
*/
PrimeBits.Set(0, false); // You don't actually need this, just
PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime
for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++)
if (PrimeBits.Get(P))
// These are going to be the multiples of P if it is a prime
for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P)
PrimeBits.Set(PMultiply, false);
// We use this to store the actual prime numbers
List<int> Primes = new List<int>();
for (int i = 2; i < Until; i++)
if (PrimeBits.Get(i))
Primes.Add(i);
也许我可以使用多个BitArray
S和BitArray.And()在一起?
这是更新的代码? – Crash893 2009-07-08 16:16:16
我知道在C#中使用多处理的最快方式是我作为另一个问题的答案提交的代码:http://stackoverflow.com/a/18885065/549617。它可以在大约0.32秒内找到总数为10亿的素数,32位数字范围内的素数总数约为1.29秒,并且在大约3秒内达到100亿的素数**不**枚举Intel i7-2700K(3.5 GHz,四核/八线程,包括超线程)。为了提供比这更快的结果,您必须使用https://code.google.com/p/primesieve/中的C代码。 – GordonBGood 2013-12-13 09:58:20