Uses the Sieve of Eratosthenes technique, and the intruiging inject() method.
This returns an array of all the primes between 2 and 1000 inclusive.

(2..1000).inject((2..1000).to_a) {|res, i| res.select{|n|n==i||n%i!=0} }

Sphere: Related Content

One Response to “Prime numbers, Ruby-style”

  1. Finnbarr Murphy says:

    This works well for small number range as above. However for a larger number range, say (2..10000000) the time taken is not linear O(n) or even squared O(nn) but is O((nlogn)(loglogn)).

Leave a Reply

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click on the image to regenerate some new text.

Anti-Spam Image