0

I'm using the formula "product of two number is equal to the product of their GCD and LCM".

Here's my code :

# Uses python3

import sys

def hcf(x, y):

    while(y):
        x, y = y, x % y

    return x

a,b = map(int,sys.stdin.readline().split())

res=int(((a*b)/hcf(a,b)))
print(res)

It works great for small numbers. But when i give input as :

Input: 226553150 1023473145

My output: 46374212988031352

Correct output: 46374212988031350

Can anyone please tell me where am I going wrong ?

Community
  • 1
  • 1
Parth Jeet
  • 129
  • 2
  • 15

2 Answers2

6

Elaborating on the comments. In Python 3, true division, /, converts its arguments to floats. In your example, the true answer of lcm(226553150, 1023473145) is 46374212988031350. By looking at bin(46374212988031350) you can verify that this is a 56 bit number. When you compute 226553150*1023473145/5 (5 is the gcd) you get 4.637421298803135e+16. Documentation suggests that such floats only have 53 bits of precision. Since 53 < 56, you have lost information. Using // avoids this. Somewhat counterintuitively, in cases like this it is "true" division which is actually false.

By the way, a useful module when dealing with exact calculations involving large integers is fractions (*):

from fractions import gcd
def lcm(a,b):
    return a*b // gcd(a,b)

>>> lcm(226553150,1023473145)
46374212988031350

(*) I just noticed that the documentation on fractions says this about its gcd: "Deprecated since version 3.5: Use math.gcd() instead", but I decided to keep the reference to fractions since it is still good to know about it and you might be using a version prior to 3.5.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • That was an amazing explanation. Thanks for that. I was not allowed to use any other library other than 'sys', that's the reason i wasn't using them. – Parth Jeet Aug 20 '16 at 14:56
1

You should use a different method to find the GCD that will be the issue:

Use:

def hcfnaive(a, b):
    if(b == 0):
        return abs(a)
    else:
        return hcfnaive(b, a % b)

You can try one more method:

import math
a = 13
b = 5
print((a*b)/math.gcd(a,b))
Anurag A S
  • 725
  • 10
  • 23
Bhaskar Gupta
  • 109
  • 1
  • 7