On 6/25/05, Florian Frank <flori / nixe.ping.de> wrote:
> Michael Tan wrote:
> 
> >So if Josef put his version in RAA , the Ruby RAA "primes" will 10 times faster than the perl CPAN one for the time being. :o)
> >
> >
> That's not necessary, it's already part of the standard library:
> 
> require 'mathn'
> p Prime.new.inject(0) { |s,x| if x > 50_000 then break s else s + 1 end }

Yeah, but that way's pretty slow.

 
joe@ubuntu:~/repos/playground/ruby $ cat primes.rb
require 'mathn'
class Integer
    def primes
        f=2
        p=[] if self <2
        p=[2] if self >=2
        3.step(self, 2) do |i|
            r = Math.sqrt(i).to_i
            p.each { |f| break if (i%f).zero? or f > r}
            p.push(i) if (i%f).nonzero?
        end # end the do block
        return p
    end
end

a=Time.now.to_f
puts 50000.primes.length
printf "time taken: %.2f seconds\n", Time.now.to_f-a

# Florian's version
b = Time.now.to_f
puts Prime.new.inject(0) { |s, x| if x > 50000 then break s else s + 1 end }
printf "time taken: %.2f seconds\n", Time.now.to_f-b


joe@ubuntu:~/repos/playground/ruby $ ruby primes.rb
5133
time taken: 0.47 seconds
5133
time taken: 13.16 seconds