Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Prime from 1 to N
# prime.rb
limit = Integer(ARGV.shift || 1000)
primes = []
#list all numbers
for i in 2 .. limit
primes[i] = i
end
for i in 2 .. Math.sqrt(limit)
next unless primes[i] #check if number already striked out or not
(i*i).step(limit, i) do |j| #Numbers like 2i, 3i, 4i, etc. can't be primes, strike them out.
primes[j] = nil
end
end
puts primes.compact.join " " #All numbers that not striked out is prime numbers :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment