Skip to content

Instantly share code, notes, and snippets.

@mnbi
Created November 5, 2010 13:18
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/664139 to your computer and use it in GitHub Desktop.
Save mnbi/664139 to your computer and use it in GitHub Desktop.
make a list of prime numbers in the specified range.
#!/opt/local/bin/ruby1.9 -w
# -*- coding: utf-8 -*-
# listprimes.rb: make a list of prime numbers.
def die(*x)
STDERR.puts x
exit 1
end
if ARGV.length < 2
die <<USAGE
Usage: #{__FILE__} <start> <range>
print prime numbers (start <= primes < start + range)
USAGE
end
start = ARGV.shift.to_i
range = ARGV.shift.to_i
PRIMES_FILE = "primes.txt"
$primes = []
if File.exist?(PRIMES_FILE)
File.foreach(PRIMES_FILE) do |line|
$primes.push(line.to_i)
end
end
$updated = false
$primes = [2] if $primes.size < 1
$max_prime = $primes[-1]
def prime_check(n)
c = 1
limit = Math::sqrt(n)
$primes.each do |p|
break if p > limit
return [false, c] if (n % p == 0)
c += 1
end
[true, c]
end
($max_prime...start).each do |n|
next if $primes.include?(n)
if prime_check(n)[0]
$primes.push(n)
$updated = true
end
end
$max_prime = $primes[-1] if $updated
print "START (#{$max_prime}):\n"
start = 2 if start < 2
t0 = Time.now
(start...(start + range)).each do |n|
if n <= $max_prime
if $primes.include?(n)
print "#{n} (0)\n"
end
else
is_prime, counter = prime_check(n)
if is_prime
$primes.push(n)
$updated = true
print "#{n} (#{counter})\n"
end
end
end
elapsed = Time.now - t0
print "Elapsed: #{elapsed}\n"
if $updated
File.open(PRIMES_FILE, "w") do |of|
$primes.each do |p|
of.puts(p)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment