ruby/ruby — pull request #736 by nslocum (2014-10-10 01:21:17+00:00)
Title: Rewrote #prime? to be much faster.

This new version executes an order of magnitude faster.

require 'benchmark'
require 'prime'

def prime?(n)
return true if n == 2
return false if n % 2 == 0 || n < 2
(3..(n**0.5).floor).step(2) { |i|
return false if n % i == 0
}
true
end

# Current Method
puts Benchmark.measure {
(1..1_000_000).each { |i| i.prime? }
}

# Improved
puts Benchmark.measure {
# Current Method
(1..1_000_000).each { |i| prime?(i) }
}

# Current Method
puts Benchmark.measure {
1000.times {
(1..1_000).each { |i| i.prime? }
}
}

# Improved
puts Benchmark.measure {
1000.times {
(1..1_000).each { |i| prime?(i) }
}
}