使用埃拉托斯特尼筛法在 C# 中查找质数






4.80/5 (5投票s)
本技巧演示了一个简单的 C# 控制台程序,它使用埃拉托斯特尼筛法算法快速查找质数。
是否曾经被要求生成质数列表,并且希望使用 埃拉托斯特尼筛法[^] 来实现,但又不确定如何在 C# 中编写代码?如果是这样,那么这个用 .NET 编写的简单控制台程序应该可以解决问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrimeFinder
{
class Program
{
static void Main(string[] args)
{
// this method encodes the Sieve of Eratosthenes
// with some intelligent shortcuts, such as excluding
// all even numbers greater than 2 etc.
try
{
List<string> outputLines = new List<string>();
// read in the numbers specified in the argument
string[] numbersList = File.ReadAllLines(args[0]);
foreach(string number in numbersList) {
int N = Int32.Parse(number);
List<int> primeCandidates = new List<int>(N);
if (N==2)
{
outputLines.Add("2\r\n"); // trivial case
continue;
}
if (N==1)
{
throw new InvalidArgumentException("The number one is trivially prime.");
}
// initialize primeCandidates with 2
// and the list of all odd numbers
// less than N -- because all even numbers
// save 2 are nonprime by definition
primeCandidates.Add(2); // the number 2 is always prime
for (int i = 2; i <= (N+1)/2; i++)
primeCandidates.Add(2*i-1);
for(int j = 0;j < primeCandidates.Count;++j) {
// initialize first prime
int prime = primeCandidates[j];
// use for loop to go through the multiples of the prime
for( int multiple = 2;multiple*prime <= N;++multiple) {
if (prime == 2) break; // duh, 2 is a prime
// skip all even multiples of 2
if ((multiple * prime) % 2 == 0)
continue;
// don't bother removing an item that
// is not even in the list
if (!primeCandidates.Contains(multiple * prime))
continue;
primeCandidates.Remove(multiple * prime);
}
}
// put together a string representing
// current output line of primes
string currentOutputLine = string.Empty;
foreach (int value in primeCandidates)
currentOutputLine += value.ToString() + ',';
currentOutputLine =
currentOutputLine.Remove(currentOutputLine.Length - 1);
currentOutputLine += "\r\n"; // Windows CRLF encoding
Console.Write(currentOutputLine);
// write a line to the output file for
// each list of prime
// candidates generated
outputLines.Add(currentOutputLine);
}
File.WriteAllLines(args[1], outputLines);
Console.WriteLine("DONE computing primes");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}