Skip to content

Instantly share code, notes, and snippets.

@mnbi
Created November 6, 2010 12:45
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 mnbi/665387 to your computer and use it in GitHub Desktop.
Save mnbi/665387 to your computer and use it in GitHub Desktop.
make a list of prime numbers using the sieve of Eratosthenes.
#!/opt/local/bin/ruby1.9 -w
# -*- coding: utf-8 -*-
# listprimes_sieve.rb: make a list of prime numbers using the sieve of Eratosthenes
start = ARGV.shift.to_i
start = 2 if start < 2
range = ARGV.shift.to_i
def sieve(start, range)
limit = start + range
max = Math::sqrt(limit).to_i
s = Array.new(limit, true)
s[0] = s[1] = false
i = step = 2
while i <= max
j = i + step
while j < limit
s[j] = false
j += step
end
i += 1
until s[i] or i > max
i += 1
end
step = i
end
primes = []
(start...limit).each do |n|
primes.push(n) if s[n]
end
return primes
end
t0 = Time.now
sieve(start, range).each do |p|
print "#{p}\n"
end
elapsed = Time.now - t0
print "Elapsed: #{elapsed}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment