编写一个程序,用1000个元素的数组确定和显示2~999之间的质数。(如何用C#语言编写)

2025-01-08 02:54:28
推荐回答(1个)
回答1:

using System;
using System.Collections.Generic;
using System.Text;

class PrimeNumber
{
public static List searchPrimeNumber(int beginNum, int endNum)
{
beginNum = beginNum <= 1 ? 2 : beginNum;
int offset = beginNum;
bool[] checkNum = new bool[endNum - beginNum + 1];
for (int i = 0; i < endNum - beginNum + 1; i++)
checkNum[i] = true;
for (int i = 0; i < endNum - beginNum + 1; i++)
{
if (checkNum[i])
{
int j = i+offset;
while (j < endNum + 1)
{
j += i + offset;
if (j< endNum+ 1 && checkNum[j - offset])
checkNum[j - offset] = false;
}
}
}
List result = new List();
for (int i = 0; i < endNum - beginNum + 1; i++)
if (checkNum[i])
result.Add(i + offset);
return result;
}

public static void Main()
{
List result = searchPrimeNumber(2, 999);
Console.WriteLine(result.Count+":");
foreach (int i in result)
Console.Write(i + " ");
while (true)
{
}
}

}