# 通过Eratosthene的筛子C#生成素数 [英] Generate Prime Numbers via Eratosthene&#39;s Sieve C#

### 问题描述

``````using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
static void Main(string[] args)
{
long maxNum = 100;
double maxSqrt = Math.Floor(Math.Sqrt(maxNum));
long basePrime;
// Make a list from 2 to maxNum
List<long> numberList = new List<long>();
List<long> sievedList = new List<long>();
for (long i = 2; i <= maxNum; i++) numberList.Add(i);
// Evaluate the first number of the list, if it is < maxSqrt skip it, create a list of multiples and Except them from numberList, else, numberList is completely Prime Factors

foreach (long number in numberList.Skip(1))
{
basePrime = numberList[0];
Console.WriteLine(basePrime);
while (number < maxSqrt)
{
if (number % basePrime == 0)
{
}
numberList = numberList.Except(sievedList).ToList();
sievedList.Clear();
}
}
Console.WriteLine("Finished Allocating Primes");
numberList.ForEach(Console.WriteLine);
}
}
``````

### 推荐答案

• 您的`numberedList`只是用for循环填充的从2到`maxNum`的整数列表。然后，您将遍历列表。只需使用for循环中的计数器即可。为了记录哪些数字是质数，BitArray(Int32, Boolean)很有效。
• 这也允许摆脱昂贵的LINQ扩展。当您找到一个非素数时，只需更改它在位数组中的索引即可。找到质数后，将其添加到列表中；