[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

rational.rb Integer#lcm correction

erlercw@siu.edu

11/15/2004 1:28:00 AM

> From: Bret Jolly (oinkoink+unet@rexx.com)
> Subject: Broken lcm
> 2004-05-20 11:05:01 PST
> Ruby version: ruby 1.9.0 (2004-05-10) [i686-linux]
> The lcm method used by mathn (and defined in rational.rb)
> is broken.
...
> irb(main):003:0> 0.lcm(0)
> ZeroDivisionError: divided by 0
...
> But the lcm of 0 and 0 is well-defined (and equal to 0).
>
> Regards, Bret

The following corrects Integer#lcm in rational.rb (with one less call to #abs, too).

def lcm(other)
if self.zero? or other.zero?
0
else
(self.div(self.gcd(other)) * other).abs
end
end




1 Answer

erlercw@siu.edu

11/15/2004 1:54:00 AM

0

Sorry, I forgot Integer#gcdlcm.

> def lcm(other)
> if self.zero? or other.zero?
> 0
> else
> (self.div(self.gcd(other)) * other).abs
> end
> end

def gcdlcm(other)
gcd = self.gcd(other)
if self.zero? or other.zero?
[gcd, 0]
else
[gcd, (self.div(gcd) * other).abs]
end
end