Python Program to Find GCD of Two Numbers using the Euclidean Algorithm

In this tutorial, we will discuss a Python program to find the GCD of two given numbers using the Euclidean algorithm.

Before going to the program first, let us understand what is Greatest Common Divisor(GCD).

Greatest Common Divisor:

  • The GCD of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

Related:Python Program to generate Fibonacci Series using Recursion

Program code to find GCD of two numbers using eucliden algorithm in Python

# GCD Using Euclidean Algorithm in Python
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

print(f"The GCD of {num1} and {num2} is {gcd(num1, num2)}.")

Explanation

  1. Function Definition: The gcd function takes two integers a and b as input and returns the GCD of the two numbers using the Euclidean algorithm.
  2. Main Program: The program prompts the user to enter two numbers and then calculates the GCD using the gcd function and prints the result.

Output

Python Program to Find GCD of Two Numbers using the Euclidean Algorithm

  • When you run the above program, it will prompt you to enter two numbers.
  • After entering the numbers, it will calculate the GCD using the Euclidean algorithm and print the result.

Conclusion

  • In this tutorial, we learned how to find the GCD of two given numbers using the Euclidean algorithm in a Python program.
  • Understanding this concept is essential for solving various mathematical problems and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *