Created
November 6, 2010 12:45
-
-
Save mnbi/665387 to your computer and use it in GitHub Desktop.
make a list of prime numbers using the sieve of Eratosthenes.
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
#!/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