pythonmathlcm

Least Common Multiple (LCM) - Python


This is not much about how do i do it and more about whats wrong with this method. I managed to solve this using other methods but i dont know why i cant with this one. what am i missing here?

Example input: 4,6 Expected output: 12 Actual output: 4

n1, n2 = map(int, input("n1 and n2: ").split(','))

def lcmCalc (n1,n2):
    i = 2
    lcm = 1
    while (n1 != 1) and (n2 != 1):
        if n1 % i == 0 and n2 % i == 0:
            lcm *= i
            n1 = n1/i
            n2 = n2/i
        elif n1 % i != 0 and n2 % i == 0:
            lcm *= i
            n2 = n2/i
        elif n1 % i == 0 and n2 % i != 0:
            lcm *= i
            n1 = n1/i
        else:
            i += 1
    return lcm

print(lcmCalc(n1,n2))

Solution

  • You were close. Here are the edits:

    def lcmCalc(n1, n2):
        i = 2
        lcm = 1
        while (n1 != 1) and (n2 != 1):
            if n1 % i == 0 and n2 % i == 0:
                lcm *= i
                n1 = n1 // i   # <== use floor division operator
                n2 = n2 // i
            elif n2 % i == 0:  # <== remove unneeded 2nd test
                lcm *= i
                n2 = n2 // i
            elif n1 % i == 0:  # <== remove unneeded 2nd test
                lcm *= i
                n1 = n1 // i
            else:
                i += 1
        return lcm * n1 * n2    # <== need to include residuals
    

    When the outer loop terminates, either of n1 or n2 may still be above 1. That residual needs to be included in the result.