2012/04/01(Sun)C# で 素数表を得る。エラトステネスのふるい

はてブ数 2012/04/01 3:57 プログラミング::C# つーさ

素数表を得る

class PrimeTable {
    public List<int> Primes = new List<int>();
    public bool[] IsPrime;
    public PrimeTable(int max) {
        IsPrime = new bool[max + 1];
        for (int i = 2; i <= max; i++) IsPrime[i] = true;
        for (int i = 2; i <= max; i++)
            if (IsPrime[i]) {
                Primes.Add(i);
                for (int j = i * 2; j <= max; j += i)
                    IsPrime[j] = false;
            }
    }
}

public class Program {
    static void Main() {
        foreach (var p in new PrimeTable(100).Primes)
            Console.WriteLine(p);
    }
}