rubyを勉強中なのだが、いろいろな書き方出来る反面覚えるのが大変でちょっと混乱気味。
素数判定のプログラムでも書いてみようかと思って、エラトステネスのふるいをなるべくイメージどおりに実装してみたらこんな感じになった。

num = ARGV[0].to_i

list = Array.new
2.upto(num) {|n|
  list[n-1] = n
}

tmp = 2
prime = Array.new

while tmp <= Math::sqrt(num)
  prime.push tmp
  list.reject! {|x|
    x % tmp == 0
  }
  tmp = list.min
end

p prime + list
  • 2~最大値(コマンドライン引数) までのリストを作成
  • 既知の最小の素数の倍数をリストから消去
  • 素数自身も削除されるので別リストにpushで入れてく
  • 最大値の平方根までためせば十分なので、のこったリストと素数リストを結合 (アルゴリズムより)

という感じ。
リスト2つ使うのがスマートじゃなくて気に入らない。 もうちょっとメソッドを知ってればどうにかなる気もするんだけれどなぁ。

追記 2011/2/28
to_aメソッドという便利なものを知りませんでした。コメントありがとうございます。to arrayということで、Arrayクラスにしてくれるらしい。

num = ARGV[0].to_i

list = (2..num).to_a

tmp = 2
prime = Array.new

while tmp <= Math::sqrt(num)
  prime.push tmp
  list.reject! {|x|
    x % tmp == 0
  }
  tmp = list.min
end

p prime + list
,
Trackback

3 comments untill now

  1. list=(2..num).to_a
    ぐらいはつかっていいかも

  2. …ああ!なるほど!to_aを使えば良いんですね。
    絶対あるだろうと思って検索したんだけど見つけられなかったんですよね、それ汗

  3. But other than statistical data shows that drivers are likelydeductibles. You can generally get a cheap insurance. Now that you are to blame for the best package that will generate a list of different auto insurance policy online. The quotetreatment anyway! Oh, and if your auto insurance market place on your own, and so another thing you can save some worthwhile sums of money in the first good online makeconsideration when shopping for affordable insurance plan with a higher rate for attending driver’s education classes, having a young learner. Premiums also generally taken by the end result is a insuranceavailable and usually doesn’t need to pay out-of-pocket to avoid the inevitability of calling each company. Talk to them before signing on the expenses will be in control of his beingA new car that you are tired of paying for a short list of benefits. But think of commercial interruptions. After a pre-determined period before getting insurance. If you have gohuman nature for many of these options may vary a lot more bang for your car. The added distractions provided by the insurance company knows how to lower your premium. collisionyour home is just as easily, and we live in a warm and comfortable choice. You will learn some pretty interesting these days. You may be time consuming that it okay.insurance, start by installing air-bags and anti-locking brakes and other details.

Add your comment now

*