1. Introduction
The greatest common divisor (GCD) of two integers is the largest positive integer that divides both numbers without a remainder. It has essential applications in number theory and is used in various domains like simplifying fractions. In this post, we will write a Python program to find the GCD of two numbers.
2. Program Overview
Our program will use Python's built-in math.gcd() method. The user will be prompted to input two numbers, and the program will then compute the GCD of these numbers and display the result.
3. Code Program
import math # Importing the math module
# Getting two numbers from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calculating the GCD using math.gcd() method
gcd = math.gcd(num1, num2)
# Displaying the GCD
print(f"The GCD of {num1} and {num2} is: {gcd}")
Output:
Enter the first number: 56 Enter the second number: 98 The GCD of 56 and 98 is: 14
4. Step By Step Explanation
1. We begin by importing the math module which contains a variety of mathematical functions including gcd().
2. We then prompt the user to input two numbers using the input() function. These numbers are converted to integers using the int() function.
3. The math.gcd() function is used to calculate the GCD of the two numbers. This method returns the greatest common divisor of the two specified integers.
4. Finally, we use the print() function to display the computed GCD to the user.
Comments
Post a Comment
Leave Comment