质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 筛法求素数 { class Program { const int Max = 100; static void Main(string[] args) { //求0到Max以内的所有素数 bool[] a = new bool[Max + 1]; for (int i = 2; i <= Max; i++) a[i] = true; //假设0~Max所有数都为素数 for (int i = 2; i <= Max; i++) { //用i遍历2~Max内的所有数 if (a[i]) { //如果i还没被筛除就求它的倍数 for (int j = 2 * i; j <= Max; j += i) a[j] = false; //j为i的倍数,将j筛除 } } for (int i = 2; i <= Max; i++) if (a[i]) Console.Write(i + " "); } } }