Prime numbers, Ruby-style
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} }
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} }
This entry was posted on Thursday, October 12th, 2006 at 5:06 am and is filed under Ruby. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
ProjectX Blog is powered by WordPress with White as Milk
designed by Azeem Azeez. Entries (RSS) and Comments (RSS).
October 5th, 2008 at 4:53 am
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)).