AdminSohel
AdminSohel

Reputation: 11

LCM of two numbers using for-loop

number1 = 6
number2 = 8
for i in range(1, number1 + 1):
    a = number1 * i
    for j in range(1, number2 + 1):
        b = number2 * j
        if b == a:
            print(number)

The compiler is returning 6 as an answer. But my expectation is to get 48

Upvotes: 1

Views: 369

Answers (1)

Michael M.
Michael M.

Reputation: 11070

First, the least common multiple of 6 and 8 is 24, not 48, so you should expect to get 24. The issue with your code is that you're returning the original number1/number2, not the calculated LCM (which is in a and b). Also, once you reach a result, you should stop both loops immediately because that number is the LCM and any further results will be multiples of the LCM. Try this instead:

def lcm(number1, number2):
    for i in range(1, number2 + 1):
        a = number1 * i
        for j in range(1, number1 + 1):
            b = number2 * j
            if b == a:
                return a


print(lcm(6, 8))  # => 24

This is fine for a homework assignment, however, this code is inefficient. It is better to use Euclid's algorithm to get the greatest common divisor, then use (number1*number2) / gcd(number1, number2) to calculate the least common multiple, like this:

def lcm(number1, number2):
    a = number1
    b = number2
    while b != 0:
        temp = b
        b = a % b
        a = temp
    return (number1*number2)//a


print(lcm(6, 8))  # => 24

Or better yet, as Mark Tolonen pointed out in the comments, use the built-in math.lcm() function from the math module. Like this:

import math

print(math.lcm(6, 8))  # => 24

Upvotes: 1

Related Questions