Learn to Code via Tutorials on Repl.it!

← Back to all posts

# LCM [Least Common Multiple] Tutorial

## Function

#### I recommend you put all this code I'm going to teach you in a function like this:

``````def LCM(n, m): # n and m are just any numbers
# code here``````

## Logic time!

### Prime factorization

#### First, we need to do the prime factorization. `12 = 2^2 * 3^1` and `40 = 2^3 * 5^1`.

``````12 = 2^2 * 3^1
40 = 2^3 * 5^1``````

We see that `2^3` is greater than `2^2`. But, there is no other number with 3 except 3^1, the same with 5. So you multiply it directly.

`2^3 * 3^1 * 5^1 = 120`. That's the answer

## Getting started (finally)

### Logic

#### We need to know which one is the greatest so we can add continuously adding to it until it is divisible by the other number. We can do that by:

``````def LCM(n, m):
global y # make it a global variable
y = n # I had to define y so here you go
if n < m: # if n is less than m
while y < n*m: # y has to be less than the product of the numbers you want to find LCM of.
y += n # keep adding n to the value of y
if y % m == 0: # every loop check if when y divided by the other number (in this case it is m), the remainder is 0 which means it could be evenly divided by it.
print(y) # if this event occurs, than print the LCM
break # exit the loop
# same thing but just opposite
elif m < n:
while y < n*m:
y += m
if y % n == 0:
print(y)
break ``````

## To use the program, simply do

``LCM(4,5) # call the function with the parameters``