埃拉托斯特尼筛法

看到有人在说这个算法,就自己随便写写了。

一、简要介绍(摘自维基百科)

埃拉托斯特尼筛法,详细列出算法如下:

  1. 列出2以后的所有序列:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  2. 标出序列中的第一个素数,也就是2,序列变成:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  3. 将剩下序列中,划摽2的倍数(用红色标出),序列变成:
    • 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
  4. 如果现在这个序列中最大数小于最后一个标出的素数的平方,那么剩下的序列中所有的数都是素数,否则回到第二步。

二、代码实现

GetPrimeNum
 1 using System;
2 using System.Collections.Generic;
3
4 namespace ConsoleApplication1
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 // TODO:1、判断是数字;2、判断<2,则无素数;>=2开始查找素数
11 int intNum = Convert.ToInt32(Console.ReadLine());
12
13 List<int> AListNum = new List<int>();
14 for (int i = 2; i < intNum + 1; i++)
15 {
16 AListNum.Add(i);
17 }
18
19 new Program().GetPrimeNum(AListNum);
20 }
21
22 public void GetPrimeNum(List<int> AListNum)
23 {
24 // 第一个数为素数
25 List<int> BListNum = new List<int>();
26 foreach (var item in AListNum)
27 {
28 BListNum.Add(item);
29 }
30 Console.WriteLine(AListNum[0]);
31
32 // 过滤掉第一个素数的倍数
33 for (int i = 0; i < AListNum.Count; i++)
34 {
35 if (AListNum[i] % AListNum[0] == 0)
36 {
37 BListNum.Remove(AListNum[i]);
38 }
39 }
40
41 // 从过滤后的数字中查找素数
42 if (BListNum.Count > 1)
43 {
44 GetPrimeNum(BListNum);
45 }
46 }
47 }
48 }

 

posted @ 2011-11-29 21:29  illday  阅读(279)  评论(0编辑  收藏  举报