Thank you for everyone who replied my first post with my first Ruby program here directly or indirectly. It is really a great community, a lot of fun. I did not expect I could learn so much. Here are some of I learned from everyone: 1) everything is object,so all are method calls (to_i, to_f, each, ...) . 2)open class even for Integer, String... ,.3) method chain , 4) .yield and code block and more. And especially I have to thank the following people:
Florian Frank : not , enum, .floor .find, inject(0)...
Ken Kunz: how to use "benchmark" , .step ,easy to understand...
Ara.T.Howard: how to write a benchmark, fork, subprocess, lambda(Proc), label ,Inline C
Josef 'Jupp' SCHUGT: best algorithm so far , array.push...
Ryan Davis:-rzenoptimize
Issues: 1) I installed zenhacks and RubyToC in order to run -rzenoptimize but failed. I will work on that later.
2) I installed win32-process to implement the "fork" method, failed. I will work on that later.
BTW, To prove nothing , just for fun, here is the results from the final version (from Josef 'Jupp' SCHUGT, i changed a little bit)
My original one: 101 seconds.
The final one: 0.48 seconds
Perl CPAN version: 5 seconds (only means the algorithm is not good)
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)
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", Time.now.to_f-a
Perl CPAN:
use Math::Big 'primes';
my $max = 50000;
my $start = time();
my $total = primes($max);
my $time = time() - $start;
print "There are $total primes below $max.\n";
print "Time taken was $time seconds\n";
···
---------------------------------
Yahoo! Sports
Rekindle the Rivalries. Sign up for Fantasy Football