In this tutorial, we will learn how to write a Python program to find the greatest common divisor (GCD) of two numbers. The GCD is the largest positive integer that divides both numbers without leaving a remainder. We will use the Euclidean algorithm to calculate the GCD.
To follow along with this tutorial, you should have a basic understanding of Python programming. If you’re new to Python, you might want to check out some beginner tutorials first.
gcd() that takes two integers, a and b, as input.def gcd(a: int, b: int) -> int:
remainder equal to the remainder of a divided by b.remainder = a % b
b, as it is the GCD.if remainder == 0:
return b
gcd() function with arguments b and remainder.return gcd(b, remainder)
gcd() function with two numbers and printing the result.num1 = 48
num2 = 18
print(f"The GCD of {num1} and {num2} is: {gcd(num1, num2)}")
The output of the program should be:
The GCD of 48 and 18 is: 6
Congratulations! You have learned how to write a Python program to find the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. This program can be useful in various mathematical calculations and problem-solving scenarios. Keep practicing and exploring more Python programming concepts to enhance your skills.
Remember to customize the code with your own numbers to calculate the GCD of different pairs.