【发布时间】:2010-09-07 01:11:21
【问题描述】:
我实际上对我的问题有一个答案,但它不是并行的,所以我对改进算法的方法很感兴趣。无论如何,它可能对某些人有用。
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);
也许我可以同时使用多个BitArrays 和BitArray.And()?
【问题讨论】:
-
我所知道的在 C# 中使用多处理的最快方法是我提交的代码作为另一个问题的答案:stackoverflow.com/a/18885065/549617。将素数总数到十亿个约0.32秒,32位数范围内的素数约1.29秒,素数到百亿个约3秒不是 在 Intel i7-2700K(3.5 GHz,四核/八线程,包括超线程)上使用枚举。为了比这更快地给出结果,必须使用 code.google.com/p/primesieve 中的 C 代码。
-
我尝试了上面的解决方案,但出现异常:'算术运算导致溢出'。 List
应该是 List . -
平方根后面不需要“+ 1”。如果它恰好向下取整,则向上取整会产生高于您的测试数字的结果。
标签: c# .net performance algorithm bitarray