How to Find GCD of Two Numbers in Python


This example is to show how to find the greatest common divisor (GCD) of two numbers in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

a = int(input("Enter the first number:"))
b = int(input("Enter the second number:"))
i = a
j = b
gcd1 = 1
while j > 0:
    k = j
    j = i % j
    i = k
else:
    gcd1 = i
    print("The GCD of the two numbers is ", gcd1)

Output:

Enter the first number:20
Enter the second number:5
The GCD of the two numbers is  5

Enter the first number:58
Enter the second number:36
The GCD of the two numbers is  2
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement