Here is  a much faster, and more standard, method for doing primality
testing and factorization in Ruby.

[Un/L]inux comes with the standard cli command "factor".

$ factor 30409113
30409113: 3 7 1448053                # here the number is composite

$ factor 6000000000000001
6000000000000001: 6000000000000001   # here the number is a prime

This can be used to create MUCH FASTER and more portable code that will
work exactly the same with all versions of Ruby run under *nix systems.

Here's the code:

class Integer
   def factors
     factors = `factor #{self.abs}`.split(' ')[1..-1].map {|i| i.to_i}
     h = Hash.new(0); factors.each {|f| h[f] +=1}; h.to_a.sort
   end

   def primality?
     return true if `factor #{self.abs}`.split(' ')[1..-1].size == 1
     return false
   end
end

2.0.0p247 :054 > 30409113.factors
 => [[3, 1], [7, 1], [1448053, 1]]

2.0.0p247 :055 > 6000000000000001.primality?
 => true

I used these names to not conflict with the other methods in my code
base.

Now Ruby can do REALLY BIG NUMBERS with consistent fast performance.

Since Ruby uses other system calls and dependencies anyway, I don't see
where this should be a problem (technically or politically), especially
for the enormous performance gains. This should even work for Windoze
builds, as they use *nix emulators.

Jabari Zakiya

-- 
Posted via http://www.ruby-forum.com/.