LoginSignup
5
6

More than 5 years have passed since last update.

Javaしか書けない雑魚がRubyで素数判定コード書いてみた

Posted at

入力した数値までの素数を表示するプログラムを自分なりに書いてみたよ

prime.rb
#Encoding: utf-8
class Prime
    def initialize(setNum)
        @setNum = setNum.to_i
        @count = 0
        @n_Number = Array.new(@setNum + 1){0}       #0なら素数。初期値は全て素数としておく
        @getSqrt = Math.sqrt(@setNum);
    end

    #@setNumの平方根までの素数の倍数を排除する
    def exclusion
        @n_Number[0] = 1
        @n_Number[1] = 1
        (2..@getSqrt).each{ |i|
            if @n_Number[i] == 0
            ((i + 1)..@setNum).each{ |j|
                @n_Number[j] = 1 if j % i == 0
            }
            end
        }
    end

    #排除の対象にならなかったものが素数である
    def getPrime
        exclusion
        (0..@setNum).each {|i|
            if @n_Number[i] == 0
                printf("%6d", i)
                @count = @count + 1
                printf("\n") if @count % 10 == 0        #10個表示したら改行する。
            end
        }
        puts ""
    end
end
print "数値:"
Prime.new(gets).getPrime

結果1

$ ruby prime.rb
数値:120
     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   101   103   107   109   113

結果2

$ ruby prime.rb
数値:200
     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   101   103   107   109   113
   127   131   137   139   149   151   157   163   167   173
   179   181   191   193   197   199

もっと短く書けそうなんだけどなー

5
6
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
5
6