Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.