0
How to make a function that calculates LCM(lowest common multiple) and HCF (highest common factor) in python
Maths
4 Respostas
+ 1
Hcf of two numbers ,
list=[]
def hcf(firstNumber,secondNumber):
i=2
result=1
while i<firstNumber:
if firstNumber%i==0 and secondNumber%i==0:
list.append(i)
firstNumber=int(firstNumber/i)
secondNumber=int(secondNumber/i)
else:
i+=1
for i in list:
result*=i
return result
print(hcf(1500,2000))
hcf is basically the multiplication of factors that appear in both numbers,
+ 1
👍
+ 1
For LCM store the factors of each numbers in a seperate list ,
Then count the number of occurrences of a number in each list and store it as a key value pair in dictionary ,
Then compare both dictionaries to see if a number occurs in both ,if yes multiply the key(number) with itself number of times the highest value either of the key has
and if a number occurs in either of dictionary , simply multiply it to the rest of result
Just how I think it could be done ,but you can try whatever way you want and then come up with a specific question if you find yourself stuck at some point
0
Thank you so much