素数を求める

id:kuripさんのところより
100までの素数を求めるプログラム

いわゆる古典ですが,C#でどう実装するのがエレガントなんだろう?

ここはやっぱり、LINQでしょう!

using System;
using System.Query;
using System.Collections.Generic;

static class Program {

    public static IEnumerable<int> GetPrimes(int max) {
        var primes = from x in Sequence.Range (1, max).Skip (1)
            where !Sequence.Range (2, x-2).Any (y => x % y == 0)
            select x;
        return primes; 
    }

    public static void Main () {
        foreach (var p in GetPrimes (100))
            Console.Write ("{0},", p);
        Console.WriteLine ();
    }
}

/*
 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,
 */

うむ。エレガントだ。うあっ、石投げないで〜

(追記) Nemerleで書くとこんな感じ。

続きを読む