Saturday, August 1, 2020

Python Program to find the LCM and HCF of Rational Numbers [ Free Code ]

*****
In this Python Program we find the LCM and HCF of two rational numbers such as 2/5 and 5/7.
The Daily code challenge is to implement Exception Handling in the program for a Divide by Zero Error.
The use of fractions Module is done here.
*****
import fractions

def lcm(x, y):
if x > y:
greater = x
else:
greater = y


while (True):
if ((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm


def hcf(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

a= fractions.Fraction(input("Enter 1st Rational no: "))
b= fractions.Fraction(input("Enter 2nd Rational no: "))

c = a.numerator
d = a.denominator
e = b.numerator
f = b.denominator
print("The lcm of",a,"and",b,"is",lcm(c,e),"/",hcf(d,f))
print("The gcd of",a,"and",b,"is",hcf(c,e),"/",lcm(d,f))