Skip to content

Instantly share code, notes, and snippets.

@tsmsogn
Last active May 6, 2019 01:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsmsogn/4e7d2768830372d30b35 to your computer and use it in GitHub Desktop.
Save tsmsogn/4e7d2768830372d30b35 to your computer and use it in GitHub Desktop.
[ruby]Sieve of Eratosthenes with Ruby
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