Greatest common divisor (GCD) and Lowest Common Multiple (LCM) of two input numbers

a=int(input("Enter first number:"))
b=int(input("Enter second number:"))

def gcd(a,b):
    if(b==0):
        return a
    else:
        return gcd(b,a%b)

GCD=gcd(a,b)
print("GCD is: ",GCD)
Output
Enter first number:85
Enter second number:20
GCD is:  5

Using Euclidean algorithm

def get_gcd(x, y):
    while y:
        x, y = y, x % y
    return x

# Example usage
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The GCD of", num1, "and", num2, "is", get_gcd(num1, num2))

Using built-in math module

import math

def get_gcd(x, y):
    return math.gcd(x, y)

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The GCD of", num1, "and", num2, "is", get_gcd(num1, num2))
Math module

Lowest Common Multiple (LCM)

The Lowest Common Multiple (LCM) of two integers is the smallest positive integer that is divisible by both of these numbers without leaving a remainder.

Without using the Math module
We can define our own function to compute the Greatest Common Divisor (GCD) first.

The LCM can be calculated by dividing the product of the two numbers by their GCD.
def get_gcd(x, y):
    while y:
        x, y = y, x % y
    return x # GCD of two numbers 

# Function to compute LCM using the GCD
def get_lcm(x, y):
    lcm = abs(x*y) // get_gcd(x, y)
    return lcm

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The LCM of", num1, "and", num2, "is", get_lcm(num1, num2))
Output
Enter first number: 20
Enter second number: 12
The LCM of 20 and 12 is 60

LCM using math module

import math

# Function to compute LCM
def get_lcm(x, y):
    return abs(x*y) // math.gcd(x, y)

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The LCM of", num1, "and", num2, "is", get_lcm(num1, num2))
Learn more about recursive functions here.
All Sample codes Strong Number Armstrong Number

Podcast on Python Basics


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer