3

I am trying to implement an LCM finding algorithm. It needs to find LCM for very large numbers.

LCM is found using the formula,

LCM(A, B) = (A * B) / GCD(A, B)

where A and B are two inputs.

Input: 226553150 1023473145
So, LCM = (226553150 * 1023473145) / 5
It should be, 46374212988031350.

But python is finding this as 46374212988031352, which is obviously an error. How to solve this problem ? python screenshot

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anand MP
  • 121
  • 1
  • 2
  • 13

1 Answers1

4

You are using floating point math, because you used the / true division operator. Floating point can only approximate large numbers, and the difference you see is a result of that.

Use // floor division instead:

>>> (226553150 * 1023473145) // 5
46374212988031350

Floor division on integers never requires conversion to float, avoiding the precision issues.

Alternatively, use the decimal module for higher-precision math with real numbers:

>>> from decimal import Decimal
>>> Decimal('226553150') * Decimal('1023473145') / Decimal('5')
Decimal('46374212988031350')

This is slower than using float.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343