module Mathn require 'mathn' Prime = Object::Prime Object.class_eval{ remove_const("Prime") } end require ARGV[0] || 'prime' require 'test/unit' class PrimeTest < Test::Unit::TestCase PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] N = 10000 def test_compare_with_mathn() my_generator = Prime::PrimeGenerator.new() mathn_generator = Mathn::Prime.new() primes = [] for i in 0..N a = my_generator.next() b = mathn_generator.next() assert_equal(b, a) primes.push(a) end assert_equal(primes, my_generator.primes().sort()) end def test_each() Prime.each_with_index{|x,i| if PRIMES[i] assert_equal(PRIMES[i], x) else break end } end def test_mathn() Mathn::Prime.class_eval{ @@primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] @@next_to_check = 103 @@ulticheck_index = 3 @@ulticheck_next_squared = 121 } mathn_generator = Mathn::Prime.new() PRIMES.each{|x| assert_equal(x, mathn_generator.next()) } GC.start() t1 = Time.now N.times{ mathn_generator.next() } t2 = Time.now p [:test_mathn, t2 - t1] end def test_primes() my_generator = Prime::PrimeGenerator.new() PRIMES.each{|x| assert_equal(x, my_generator.next()) } GC.start() t1 = Time.now N.times{ my_generator.next() } t2 = Time.now p [:test_primes, t2 - t1] end def test_mathn_each() Mathn::Prime.class_eval{ @@primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] @@next_to_check = 103 @@ulticheck_index = 3 @@ulticheck_next_squared = 121 } mathn_generator = Mathn::Prime.new() c = 1 GC.start() t1 = Time.now mathn_generator.each{|x| break if c == N c += 1 } t2 = Time.now p [:test_mathn_each, t2 - t1] end def test_primes_each() c = 1 GC.start() t1 = Time.now Prime.each{|x| break if c == N c += 1 } t2 = Time.now p [:test_primes_each, t2 - t1] end #def test_regexp() # assert_equal(PRIMES, (2..100).select{|n| "1" * n !~ /^(11+)\1+$/ }) # t1 = Time.now # (2..N).select{|n| "1" * n !~ /^(11+)\1+$/ } # t2 = Time.now # p [:test_regexp, t2 - t1] #end end