How to Find the GCD of Two Numbers in Python

In this tutorial, we will learn how to find the Greatest Common Divisor (GCD) of two numbers in Python. The GCD of two integers is the biggest number that divides both of them without leaving any remainder. Python has a built-in function for calculating GCD which is gcd() and is available in the math module.

Step 1: Import math module

To begin, we need to import the math module. This can be done using the following code:

Step 2: Input Two Numbers

Next, we prompt for two integer inputs from the user using the built-in input() function.

Step 3: Use gcd() Function

After getting the two input numbers, we use the gcd() function to get the greatest common divisor. The gcd() function takes two parameters and returns their GCD.

Step 4: Display the GCD

The final step is to output the calculated GCD to the user. We can do this using the print() function.

Full Python Code

After applying these steps, the full Python code to calculate the GCD of two integers becomes:

Running the Python Code

Output:

Enter first number: 48
Enter second number: 36
The GCD of the numbers is: 12

Conclusion

And that’s it! We’ve successfully written a Python program that can find the greatest common divisor (GCD) of two numbers. This is a fundamental concept in number theory and has many applications in fields such as cryptography. Sharpening your Python skills and understanding how to apply built-in functions such as gcd() can greatly enhance your programming skill set.