Skip to content

Instantly share code, notes, and snippets.

@ballpointcarrot
Created April 18, 2011 04:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ballpointcarrot/924790 to your computer and use it in GitHub Desktop.
Save ballpointcarrot/924790 to your computer and use it in GitHub Desktop.
A comparison between the mathn library in Ruby and a self-built solution for prime generation.
require 'mathn'
# Generates a list of primes below a given value
def primelist(n)
k = 1
a = [2,3]
while 6*k < n
a.push(6*k-1)
a.push(6*k+1)
k += 1
end
count = 0
y = a[count]
while y < (n**(0.5))
a.collect!{|x| x if x % y != 0 or x == y}.compact!
count += 1
y = a[count]
end
a
end
#using the mathn library
def primeslib(n)
Prime.each(n).to_a
end
def runner(type)
puts "#{type}:\n"
ti = Time.now
puts "Start time: #{ti}\n"
yield
tf = Time.now
puts "End time: #{tf}\n"
puts "Difference in time: #{tf-ti}\n"
end
runner("Hand-rolled") {puts primelist(2000000).inject{|sum,a| sum += a}}
runner("mathn") {puts primeslib(2000000).inject{|sum,a| sum += a}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment