hey all,
so while Jesus’s implementation works, unless you want to implement a
prime number generator yourself you’re probably better off using Rubys
built-in Prime class (doc here:
http://rdoc.info/stdlib/prime/1.9.2/frames )
to do this. not only does it give you cleaner code, it is SIGNIFICANTLY
faster.
the spiffified code
require ‘prime’ # you’re gonna need this
require ‘mathn’ # you’re gonna want this
class PrimeFactor
def initialize(number)
@number = number
end
def primeFactors
@factors = Prime.prime_division(@number,
Prime::TrialDivisionGenerator.new).flatten.uniq.sort.join(', ')
end
end
#prime = PrimeFactor.new(13195)
prime = PrimeFactor.new(ARGV.shift.to_i)
puts “#{prime.primeFactors}”
in fact, benchmarking the two thusly:
the benchmark code:
require ‘prime’ # you’re gonna need this
require ‘mathn’ # you’re gonna want this
require ‘benchmark’
class PrimeFactor_Long
def initialize(number)
@number = number
end
def primeFactors
factors = Array.new
(2…@number).each do |num|
if ( @number % num == 0 )
factors.insert(factors.length,num)
end
end
# p factors
factors.each do |factor|
next if factor.nil?
factors.each_with_index do |candidate,i|
next if candidate == factor
next if candidate.nil?
factors[i] = nil if candidate % factor == 0
end
end
factors.compact.join(‘,’)
end
end
class PrimeFactor_Shrt
def initialize(number)
@number = number
end
def primeFactors
factors = Prime.prime_division(@number,
Prime::TrialDivisionGenerator.new).flatten.uniq.sort.join(', ')
end
end
lots = 13195
bunches_of = 1_000
Benchmark.bmbm do |x|
x.report(‘Long’) do
bunches_of.times do
long = PrimeFactor_Long.new lots
long.primeFactors
end
end
x.report(‘Shrt’) do
bunches_of.times do
shrt = PrimeFactor_Shrt.new lots
shrt.primeFactors
end
end
end
puts
long = PrimeFactor_Long.new lots
puts “long factors: #{long.primeFactors}”
shrt = PrimeFactor_Shrt.new lots
puts “shrt factors: #{long.primeFactors}”
gives this:
serialhex@livecd:~/src/test> ruby bench_prime.rb
Rehearsal ----------------------------------------
Long 3.160000 0.070000 3.230000 ( 3.523138)
Shrt 0.050000 0.000000 0.050000 ( 0.070737)
------------------------------- total: 3.280000sec
user system total real
Long 3.010000 0.030000 3.040000 ( 3.227173)
Shrt 0.060000 0.000000 0.060000 ( 0.070470)
long factors: 5,7,13,29
shrt factors: 5,7,13,29
no joke… it’s more than 50x faster so yeah, unless this is a
project
for a class or something, use the included Prime class!
hex
2011/3/23 Jess Gabriel y Galn [email protected]