Created
September 3, 2015 14:21
-
-
Save junpeitsuji/9bf7ee427ccb092c64e5 to your computer and use it in GitHub Desktop.
エラトステネスの篩を実行するコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
maximum_number = 10000000 | |
# 得られた素数を保管する配列 | |
primes = [] | |
# 素数の候補となる数の配列 | |
numbers = (2..maximum_number).to_a | |
p = numbers.first | |
while p*p <= maximum_number | |
# 素数の候補から先頭の数を取得する | |
p = numbers.first | |
last = numbers.last | |
# p は素数なので素数の配列に加える | |
primes.push p | |
# (p の倍数) の配列を作る | |
multiples_of_p = [] | |
multiple = p | |
while multiple <= last | |
multiples_of_p.push multiple | |
multiple += p | |
end | |
# 素数の候補から (p の倍数) を取り除く(篩にかける) | |
numbers = numbers - multiples_of_p | |
end | |
# 残った素数候補を配列に追加 | |
primes = primes + numbers | |
# 素数の配列を出力 | |
p primes | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment