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:
1 2 |
import math |
Step 2: Input Two Numbers
Next, we prompt for two integer inputs from the user using the built-in input() function.
1 2 3 |
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) |
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.
1 2 |
gcd = math.gcd(a, b) |
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.
1 2 |
print("The GCD of the numbers is: ", gcd) |
Full Python Code
After applying these steps, the full Python code to calculate the GCD of two integers becomes:
1 2 3 4 5 6 7 8 |
import math a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) gcd = math.gcd(a, b) print("The GCD of the numbers is: ", gcd) |
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.