因此,我创建了以下方法来查找不超过某个数字的所有素数。关于如何加快速度的任何建议?
我这样称呼它;
interval = (value + NOOFTHREADS - 1) / NOOFTHREADS;
int max = interval * NOOFTHREADS;
tickets = new List<int>(NOOFTHREADS);
for (int i = 1; i <= NOOFTHREADS; i++)
{
tickets.Add(i * (max / NOOFTHREADS));
}
Enumerable.Range(1, NOOFTHREADS)
.AsParallel()
.ForAll(_ => findPrimes());
带有一些全局变量;
static List<int> vals = new List<int>();
static List<int> tickets;
static int interval = new int();
以及方法;
public static void findPrimes()
{
int myTicket;
lock (tickets)
{
myTicket = (int)tickets.Last();
tickets.RemoveAt(tickets.Count - 1);
}
var max = myTicket;
int min = max - interval +1;
int num;
var maxSquareRoot = Math.Sqrt(max);
var eliminated = new System.Collections.BitArray(max + 1);
eliminated[0] = true;
eliminated[1] = true;
for (int i = 2; i < (max) / 2; i++)
{
if (!eliminated[i])
{
if (i < maxSquareRoot)
{
num = ((min + i -1 )/i)*i;
if (num == i)
num = num + i;
for (int j =num; j <= max; j += i)
eliminated[j] = true;
}
}
}
for (int b = (int)min; b < max; b++)
{
if (!eliminated[b])
lock(vals)
vals.Add(b);
}
}