Last active
March 8, 2016 18:30
-
-
Save marinhero/b37340f8e8ae073e79fb to your computer and use it in GitHub Desktop.
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 populate_array(n) | |
arr = Array.new(n, true) | |
arr[0] = false | |
arr[1] = false | |
arr | |
end | |
def print_array(a) | |
count = 0 | |
while count < a.length | |
puts "#{count} is prime" if a[count] | |
count += 1 | |
end | |
end | |
def mark_factors(a, count) | |
mult = 2 | |
while count * mult <= a.length | |
a[count * mult] = false | |
mult += 1 | |
end | |
a | |
end | |
def sieve(a) | |
count = 2 | |
while count <= Math.sqrt(a.length) | |
a = mark_factors(a, count) if a[count] | |
count += 1 | |
end | |
end | |
def main | |
puts 'Give me the limit for your primes' | |
n = Integer(gets.chomp) | |
a = populate_array(n + 1) | |
sieve(a) | |
print_array(a) | |
end | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment