rational.rb Integer#lcm correction

E

erlercw

From: Bret Jolly ([email protected])
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
 
E

erlercw

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top