Learn to Code via Tutorials on Repl.it!

← Back to all posts
LCM [Least Common Multiple] Tutorial
IcynHackz (722)

LCM [Least Common Multiple] Tutorial

Let's get started! 😉


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

First do that.

Logic time!

So...most of you should know how to find the LCM between 2 numbers. If you don't, I'll teach you.

Prime factorization

You need to do prime factorization of the numbers you are going to do the LCM for(if you don't know how to do prime factorization, then too bad. XD). Remember use the exponent way, like 2^3*4^2 (note that ^ is to the power of), don't do 2*2*2*4*4.

After you did that, you need to find the greatest exponent for the same base. (base is like 2^3, 2 is the base, 3 is the exponent) Do this for each individual base. If you come to a situation where you have like a 5^2, but the other number does not have that prime factor, then you just choose that one.

Finally, multiply all the ones you chose. That's it.

Here's a example to help you.

What is the LCM(12, 40)?

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

But that doesn't have anything to do with this tutorial!


This tutorial is much easier and simpler.

Getting started (finally)


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:

To use the program, simply do

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

You could also add things to the program like colors, etc.

Note that if the number is too big, the program will return an error, so you might want to add some try and except to it.

That's it everyone! Bai!🤗