Last active
May 6, 2019 01:45
-
-
Save tsmsogn/4e7d2768830372d30b35 to your computer and use it in GitHub Desktop.
[ruby]Sieve of Eratosthenes with Ruby
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 primes(max) | |
nums = Array.new(max + 1, 1) | |
nums[0] = nums[1] = 0 | |
(2..Math.sqrt(max)).each do |sieve| | |
if nums[sieve] == 1 | |
(2 * sieve).step(max, sieve).each do |num| | |
nums[num] = 0 | |
end | |
end | |
end | |
(2..max).select { |num| nums[num] == 1 } | |
end | |
puts primes(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] | |
start = Time.now | |
primes(1_000_000) | |
puts Time.now - start | |
#=> 0.363797 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment