Search code examples
python-3.xlcm

To find lcm without gcd algorithm-regarding


I tried it,but eventually I wrote a program for more than 30 lines.So, I looked for solution on geeksforgeeks,

def findLCM(a, b): 
    lar = max(a, b) 
    small = min(a, b) 
    i = lar 
    while(1) : 
        if (i % small == 0): 
            return i 
        i += lar 

Can anyone explain me the logic behind 'i += lar' I hope I was clear with the question. I'm welcome to any suggestions that are reasonably simple since I'm a beginner. Thank You


Solution

  • while(1) : 
        if (i % small == 0): 
            return i 
        i += lar 
    

    This is weird and un-pythonic. Just do

    while i % small != 0:
       i += lar
    return i
    

    i += lar is (for the purpose of this example) equivallent to i = i + lar.

    If you are asking for the algorithmic logic, then think about it. You are trying to find the least common multiple. So you start by checking if the smaller number evenly divides the larger one (in other words, is the larger number already the least common multiple). If not, you accumulate multiples of the larger number until you find the one that the smaller number does evenly divide, and return it.

    BTW, if we are already making this code more pythonic, the function name should be find_lcm.