Do you remember back in your first classes in university when you was taught how to calculate a series of prime numbers in C or Pascal? Do you remember those tens of lines of code?
You need a lot less in Ruby:
def primes(up_to) prev = [] (2..up_to).select do |x| max_p = Math.sqrt(x).truncate if !prev.find { |y| y <= max_p ? x % y == 0 : break } prev << x end end end
Let's try it:
irb> primes(10) => [2, 3, 5, 7] irb> primes(100) => [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] irb>
The method goes beyond naive approaches, testing each number only with previously found prime numbers that are not greater than its square root. On my machine it computes the primes up to 100,000 in under 3 seconds.
0 comments:
Post a Comment