Search code examples
pythonpython-3.xlcm

long integers division error in python while finding least common multiple


Normally, program doesn't throw an error for small however when it comes to these numbers it returns wrong division result

def leastCommonMultiple(n1, n2):
    a=n1
    b=n2
    while n2!=0:
        (n1, n2) = (n2, n1 % n2)
   print (n1) # greatest common divisior for given input is 5
   print(a*b) # for given numbers 231871064940156750
   return int((a*b)/n1) #wrong result    46374212988031352



numStr=input()
nums=numStr.split()
num1=int(nums[0])
num2=int(nums[1])
lcm=leastCommonMultiple(num1, num2)
print (lcm)


Input:
226553150 1023473145

Your output:
46374212988031352

Correct output:
46374212988031350

WHAT I WROTE EXPLANATION:

leastCommonMultiple = (Num1*Num2)/greatestCommonDivisor

So in while loop I found greatestCommonDivisor by using euclidean method

and I used the formula (LCM = n1*n2/ GCD )

I hope I explained the problem clearly. What can I solve this problem can you help me please?


Solution

  • use // in python 3 for integer division. I just found out this