0

How to make a function that calculates LCM(lowest common multiple) and HCF (highest common factor) in python

Maths

26th May 2020, 7:37 PM
Jeremy
Jeremy - avatar
4 odpowiedzi
+ 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,
26th May 2020, 8:43 PM
Abhay
Abhay - avatar
+ 1
👍
26th May 2020, 8:48 PM
Abhay
Abhay - avatar
+ 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
26th May 2020, 9:12 PM
Abhay
Abhay - avatar
0
Thank you so much
26th May 2020, 8:48 PM
Jeremy
Jeremy - avatar