Here's a version that skips even numbers:
class Integer
def is_prime?
return false if self < 2
return false if self % 2 == 0
max_factor = Math.sqrt(self).to_i
3.step(max_factor, 2) {|i| return false if self % i == 0 }
return true
end
end
And here's a benchmark comparison:
require 'benchmark'
Benchmark.bm(12) do |x|
x.report("original:") { 2.upto(50000) {|i| is_prime(i) } }
x.report("Florian's:") { 2.upto(50000) {|i| i.prime? } }
x.report("Ken's:") { 2.upto(50000) {|i| i.is_prime? } }
end
user system total real
original: 171.767000 0.020000 171.787000 (174.627000)
Florian's: 2.804000 0.010000 2.814000 ( 2.814000)
Ken's: 1.041000 0.000000 1.041000 ( 1.042000)
What's more important, how fast a program _runs_, or how fast I can
_write_ it? With Ruby, I can almost always write something that is
"fast enough", and I can write it a whole lot quicker than in Java or
C. The above (semi-) optimized version only took 2 minutes to write.
(And as a side note... it was more fun to write it in Ruby )
And when you need some extra umph... there's always YARV or ruby2c...
and when you really need it (rarely), manually optimized C.
Cheers,
Ken