我試圖解決一個問題,就是要找到給定範圍內每個數字都是素數的所有素數。使用PLINQ可以排除任何額外的效率嗎?
例如在範圍[1, 100]
答案是8
,因爲2, 3, 5, 7, 23, 37, 53, 37
都是滿足它的數字。
我目前的解決方案是正確的
// Yields all the numbers in the range [start, end] that could be primes,
// by taking into account the fact that a prime is either 2, 3, 6k + 1 or 6k - 1
static IEnumerable<long> PossiblePrimeNumbers(long start, long end)
{
if(start <= 2 && end >= 2)
yield return 2;
if(start <= 3 && end >= 3)
yield return 3;
for(long n = (start/6 + 1) * 6; ; n += 6)
{
if((n - 1) <= end)
yield return (n - 1);
if((n + 1) <= end)
yield return (n + 1);
else break;
}
}
// Map for fast checking of whether a digit 0, 1, ..., 9 is a prime
static bool[] IsPrimeDigit = { false, false, true, true, false, true, false, true, false, false };
// True or false depending on whether m is prime
static bool IsPrime(long m)
{
long boundary = (long)Math.Floor(Math.Sqrt(m));
bool isPrime = true;
for(long i = 2; i <= boundary; ++i)
{
if(m % i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
// True or false depending on whether all the digits of m are prime and
// whether m itself is prime
static bool IsMegaprime(long m)
{
return m.ToString().All(c => IsPrimeDigit[c - '0']) && IsPrime(m);
}
// Counts the number of "megaprimes" (defined above) in the range [first, last]
static int NumberMegaprimes(long first, long last)
{
return PossiblePrimeNumbers(first, last).AsParallel().Count(m => IsMegaprime(m));
}
static void Main(String[] args)
{
long first = 1;
long last = 100;
Console.WriteLine(NumberMegaprimes(first, last)); // should print 8
}
,你甚至可以看到我已經添加了.AsParallel()
,試圖加快速度。
有沒有什麼明顯的方法可以加快速度? (除了擺脫LINQ的)
這是Code Review的工作之一,因爲代碼工作,我會說。 –