素数を求める
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で書くとこんな感じ。
using System; def GetPrimes (max) { def primes = $ [ x | x in $ [2 .. max], !($ [2 .. x - 1]).Exists (fun (y) { x % y == 0 }) ]; primes; } GetPrimes (100).Iter (fun (x) { Console.Write ($ "$x,") }); Console.WriteLine (@" 「素数」は1と自分の数でしか割ることのできない孤独な数字…… わたしに勇気を与えてくれる");
記号が多めになるので個人的にはLINQの方が好みかな。
ちなみにネタ優先なのでアルゴリズム的には無駄があります。(^^;