From: David Mitchell Date: 2005-06-22T05:32:55+09:00 Subject: Re: 1. Ruby result: 101 seconds , 2. Java result:9.8 seconds, 3. Perl result:62 seconds Yeah, Ruby is always going to be slower than java, since java is semi-compiled, whereas Ruby is interpreted from scratch. As for your algorithm, it is sufficient to change your is_prime methods from: for i in 2...number to for i in 2..Math.sqrt(number).to_i Which will significantly reduce the number of tests you will perform. David Michael Tan wrote: > Just new to Ruby since last week, running my same functional program on the windows XP(Pentium M1.5G), the Ruby version is 10 times slower than the Java version. The program is to find the prime numbers like 2, 3,5, 7, 11, 13... Are there setup issues? or it is normal? > 1. Ruby result: 101 seconds > 2. Java result:9.8 seconds > 3. Perl result:62 seconds > > > Ruby: > > def is_prime(number) > for i in 2..(number-1) > if number%i==0 then return false > end > end > return true > end > ######### star here:How many primes in 2 to 50000? > max_number=50000 > start_number=2 > total=0 > time=Time.now.to_i > for i in start_number..max_number > if is_prime(i) > #puts i > total+=1 > end > end > time=Time.now.to_i-time > puts "There are #{total} primes between #{start_number} and #{max_number}" > puts "Time taken #{time} seconds" > > > Java : > import java.io.*; > class prime > { > private static boolean isPrime(long i) > { > for(long test = 2; test < i; test++) > { > if((i%test) == 0) > { > return false; > } > } > return true; > } > public static void main(String[] args) throws IOException > { > long start_time = System.currentTimeMillis(); > long n_loops = 50000; > long n_primes = 0; > for(long i = 2; i <= n_loops; i++) > { > if(isPrime(i)) > { > n_primes++; > } > } > > long end_time = System.currentTimeMillis(); > System.out.println(n_primes + " primes found"); > System.out.println("Time taken = " + (end_time - start_time)+ "millseconds"); > } > } > > > Perl: > > ######### star here:How many primes in 2 to 50000? > > # start timer > > $start = time(); > > $max_number=50000; > > $start_number=2; > > $total=0; > > for ($ii=$start_number;$ii<=$max_number;$ii++){ > > if (&is_prime($ii)==1) > > {$total+=1} > > } > > # end timer > > $end = time(); > > # report > > print "There are ",$total," primes between ",$start_number," and ",$max_number,"\n"; > > print "Time taken was ", ($end - $start), " seconds"; > > sub is_prime() { > > my ($number) = $_[0]; > > my ($si)=2; > > for ($si;$si<$number;$si++){ > > if ($number % $si == 0) { > > return 0;} > > } > > return 1 > > } > > > > > --------------------------------- > Discover Yahoo! > Find restaurants, movies, travel & more fun for the weekend. Check it out! -- David Mitchell Software Engineer Telogis