Last active
April 30, 2018 01:42
-
-
Save obelisk68/a872590c9cc730be563178bea1b1683c to your computer and use it in GitHub Desktop.
省メモリで「エラトステネスの篩」同等の結果を得るコード
This file contains hidden or 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 prime_table(n) | |
return [] if n < 2 | |
return [2] if n == 2 | |
table = [2, 3] | |
i, step = 5, 2 | |
while i <= n | |
guard = Math.sqrt(i).to_i | |
table.each do |prime| | |
break if (i % prime).zero? | |
if prime > guard | |
table << i | |
break | |
end | |
end | |
i += step | |
step = 6 - step | |
end | |
table | |
end | |
prime_table(1000_0000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment