1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで素数を出力する〜エラトステネスの篩(ふるい)〜

Posted at

こんにちは、Ruby歴半年のプログラマです。

基本的なアルゴリズムを習得したいと考えて、『Pythonではじめるアルゴリズム入門 伝統的なアルゴリズムで学ぶ定石と計算量』(以下、Pythonではじめるアルゴリズム入門)を読んでいます。

『Pythonではじめるアルゴリズム入門』では、その書籍名の通りPythonでサンプルコードが実装されているので、Rubyの練習のためにRubyに書き換えた上でアレンジを加えました。

より良い書き方などありましたら教えてもらえると嬉しいです。

環境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.4
BuildVersion:   19E287
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]

Ruby版エラトステネスの篩(ふるい)

def get_prime(input_number)
  return [] if input_number <= 1

  # 素数リスト
  under_limit_prime = [2]

  # 探索リスト(2以上の偶数は素数にはなりえないので3以上の奇数のみ)
  upper_limit_prime = (2...input_number).select(&:odd?)

  # 探索の上限値は与えられた数の平方根
  limit = Math::sqrt(input_number).floor

  # 探索リストの先頭が上限値より大きくなるまで繰り返す
  while limit > upper_limit_prime[0]
    under_limit_prime << upper_limit_prime[0]
    # 探索リストから探索リストの先頭で割り切れる数値を削除する
    upper_limit_prime.reject! { |number| number % upper_limit_prime[0] == 0  }
  end
  under_limit_prime + upper_limit_prime
end

print get_prime(200)
# [2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 57, 59, 61, 67, 69, 71, 73, 79, 83, 87, 89, 93, 97, 101, 103, 107, 109, 111, 113, 123, 127, 129, 131, 137, 139, 141, 149, 151, 157, 159, 163, 167, 173, 177, 179, 181, 183, 191, 193, 197, 199]
1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?