Skip to content

Instantly share code, notes, and snippets.

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