Created
April 5, 2019 15:59
-
-
Save yysaki/71b873ef70415459b78ad5b62625c6fe 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
def sieve(num) | |
ary = Array.new(num, true) | |
ret = [] | |
ary.each_with_index do |b, i0| | |
next if i0 == 0 || !b | |
p = i0+1 | |
ret.push p | |
i0.step(num, p) do |mark| | |
ary[mark] = false | |
end | |
end | |
ret | |
end | |
p sieve 100 | |
# [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] | |
require 'prime' | |
p Prime.each(100).map {|p| p} | |
# [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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment