Created
December 29, 2011 10:59
-
-
Save dpsk/1533526 to your computer and use it in GitHub Desktop.
Prime from 1 to N
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
# 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