Skip to content

Instantly share code, notes, and snippets.

@yysaki
Created April 5, 2019 15:59
Show Gist options
  • Save yysaki/71b873ef70415459b78ad5b62625c6fe to your computer and use it in GitHub Desktop.
Save yysaki/71b873ef70415459b78ad5b62625c6fe to your computer and use it in GitHub Desktop.
エラトステネスの篩
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