最近有个朋友问我"输出N以内素数的方法", 我想网上一定有很多方法, 而且代码有可能很雷同. 不过还是自己写了一段.
贪心法明显要快很多.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
//普通方法
public static List<int> GetPrimeList(int maxNum)
{
List<int> primeList = new List<int>();
primeList.Add(2);
for (int onCheck = 3; onCheck <= maxNum; ++onCheck)
{
bool isPrime = true;
for (int checker = 2; checker <= Math.Sqrt(onCheck); ++checker)
{
if (0 == onCheck % checker)
{
isPrime = false;
break;
}
}
if (true == isPrime)
{
primeList.Add(onCheck);
}
}
return primeList;
}
//贪心法
public static List<int> GetPrimeList(int maxNum, bool useGreedy)
{
List<int> primeList = new List<int>();
if (true == useGreedy)
{
bool[] map = new bool[maxNum + 1];
for (int i = 2; i <= maxNum; ++i)
{
map[i] = true;
}
for (int i = 2; i <= Math.Sqrt(maxNum); ++i)
{
if (true == map[i])
{
for (int j = i*i; j <= maxNum; j += i)
{
map[j] = false;
}
}
}
for (int i = 2; i <= maxNum; ++i)
{
if (true == map[i])
{
primeList.Add(i);
}
}
}
else
{
primeList = GetPrimeList(maxNum);
}
return primeList;
}
static void Main(string[] args)
{
int timeStart = DateTime.UtcNow.Minute * 60 + DateTime.UtcNow.Second;
List<int> primes = GetPrimeList(100000000,true);
int timeEnd = DateTime.UtcNow.Minute * 60 + DateTime.UtcNow.Second;
//foreach (int item in primes)
//{
// Console.Write("{0},", item);
//}
//Console.Write("\n");
Console.WriteLine("primes cont: {0}, used {1} second",primes.Count, timeEnd-timeStart);
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
//普通方法
public static List<int> GetPrimeList(int maxNum)
{
List<int> primeList = new List<int>();
primeList.Add(2);
for (int onCheck = 3; onCheck <= maxNum; ++onCheck)
{
bool isPrime = true;
for (int checker = 2; checker <= Math.Sqrt(onCheck); ++checker)
{
if (0 == onCheck % checker)
{
isPrime = false;
break;
}
}
if (true == isPrime)
{
primeList.Add(onCheck);
}
}
return primeList;
}
//贪心法
public static List<int> GetPrimeList(int maxNum, bool useGreedy)
{
List<int> primeList = new List<int>();
if (true == useGreedy)
{
bool[] map = new bool[maxNum + 1];
for (int i = 2; i <= maxNum; ++i)
{
map[i] = true;
}
for (int i = 2; i <= Math.Sqrt(maxNum); ++i)
{
if (true == map[i])
{
for (int j = i*i; j <= maxNum; j += i)
{
map[j] = false;
}
}
}
for (int i = 2; i <= maxNum; ++i)
{
if (true == map[i])
{
primeList.Add(i);
}
}
}
else
{
primeList = GetPrimeList(maxNum);
}
return primeList;
}
static void Main(string[] args)
{
int timeStart = DateTime.UtcNow.Minute * 60 + DateTime.UtcNow.Second;
List<int> primes = GetPrimeList(100000000,true);
int timeEnd = DateTime.UtcNow.Minute * 60 + DateTime.UtcNow.Second;
//foreach (int item in primes)
//{
// Console.Write("{0},", item);
//}
//Console.Write("\n");
Console.WriteLine("primes cont: {0}, used {1} second",primes.Count, timeEnd-timeStart);
Console.Read();
}
}
}