-4

Here c and d basically represent tables of respective number for variable a and b...i am trying to match the least common product from these table.Please help me figure it out

a=(input('your first no: '))
b=(input('your second no: '))

for i in range(1,100):
    c=a*i
    d=b*i
    if (c==d):
    print('lcm is')
  • Does this answer your question? [To find the lcm of two numbers](https://stackoverflow.com/questions/37813586/to-find-the-lcm-of-two-numbers) – DaVinci May 31 '20 at 11:17

2 Answers2

0

Here is a program that will work. It will also calculate the LCM of more than two numbers.

from collections import Counter
from operator import mul
from functools import reduce


def primeFactors(n):
    if not isinstance(n, int) or n < 1:
        raise ValueError("must be positive integer")
    factors = []
    while n % 2 == 0: 
        factors.append(2)
        n /= 2
    i = 3
    while n != 1:
        while n % i == 0: 
            factors.append(i)
            n /= i
        i += 2
    return factors


def get_lcm(numbers):
    factorisations = [Counter(primeFactors(n)) for n in numbers]
    primes = frozenset().union(*(set(x.keys()) for x in factorisations))
    primes_to_max_powers = (p ** max(*(x.get(p,0) for x in factorisations))
                            for p in primes)
    return reduce(mul, primes_to_max_powers, 1)


a = int(input('your first no: '))
b = int(input('your second no: '))

print('lcm is', get_lcm([a, b]))

Or you can do this instead but it might be a bit slower:

a = input('your first no: ')
b = input('your second no: ')
for i in range(max(a, b), a * b + 1):
    if i % a == 0 and i % b == 0:
        lcm = i
        break
print('lcm is ', lcm)
alani
  • 12,573
  • 2
  • 13
  • 23
0

Use the formula lcm(a,b) = ab / gcd(a,b). Python has a gcd function in the standard library:

from fractions import gcd

def least_common_multiple(a, b):
    return a * b / gcd(a, b)

Since Python 3.6, it's arguably preferable to use the gcd builtin from math:

try:
    from math import gcd
except ImportError:
    from fractions import gcd

def least_common_multiple(a, b):
    return a * b / gcd(a, b)
tiwo
  • 3,238
  • 1
  • 20
  • 33