LoginSignup
4

More than 5 years have passed since last update.

Rubyでエラトステネスの篩を書いた

Last updated at Posted at 2014-03-15

コード

初めの配列を作るところが泥臭い

max = 100

#2~maxまでの配列をつくる
# ans_array = (2..max).to_aの方法でもOK
ans_array = [*2..100]

# maxの平方根までループする
2.upto(Math.sqrt(max)) do |num|
    # 素数の倍数を削除する
    ans_array.reject! { |elem| (elem % num == 0) && (elem > num) }
end

p ans_array

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4