Skip to content

Instantly share code, notes, and snippets.

@kira924age
Created October 20, 2017 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kira924age/35cc9a40bb80c403641f881a4f05c6fa to your computer and use it in GitHub Desktop.
Save kira924age/35cc9a40bb80c403641f881a4f05c6fa to your computer and use it in GitHub Desktop.
Sieve of Eratosthene
def era(n)
$primes = Array.new(n, true)
$primes[0], $primes[1] = false, false
(2..Math.sqrt(n)).each do |i|
if $primes[i]
(i * i).step(n, i).each do |j|
$primes[j] = false
end
end
end
end
max = 1000000
era(max)
loop do
n = gets.to_i
if n == 0
break
end
number_of_primes = $primes.slice(0..n).count(true)
puts "There are #{number_of_primes} prime numbers."
puts (0..n).select{|i| $primes[i]}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment