Created
October 20, 2017 11:57
-
-
Save kira924age/35cc9a40bb80c403641f881a4f05c6fa to your computer and use it in GitHub Desktop.
Sieve of Eratosthene
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 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