Write A Simple Python Function To GCD Of Two Integers Inputted By The User

Greatest Common Divisor(GCD) is the highest number that divides two given non zero integers completely.

Given two numbers (non zero) your task is to find the highest number that will divide both the numbers completely using a python program. Let's try to solve this problem using the Euclidean algorithm.

 

Write A Simple Python Function To GCD Of Two Integers Inputted By The User


 Write A Simple Python Function To GCD Of Two Integers Inputted By The User

Define a function find_gcd() with two numbers as input argument a and b. Use the while loop until b becomes zero, set the value of a as b and value of b as b % a.

After the while loop completes variable a will store the GCD of two numbers. Return the variable a as function find_gcd() return value

def find_gcd(a, b):
   while b != 0:
       a, b = b, a % b
   return a




Take two integer variables x and y and use input() function call to ask the user to enter the first and second number, convert it to integer using type conversion.

x = int(input("Enter a First Number : "))
y = int(input("Enter a Second Number : "))




Take a variable gcd and call the function find_gcd() by providing two integer values x and y. Once the function is completed print the gcd of two numbers using print() function call.

gcd = find_gcd(x, y)
print("GCD of two numbers is : ", gcd)




Complete Program
=================

def find_gcd(a, b):
   while b != 0:
       a, b = b, a % b
   return a


x = int(input("Enter a First Number : "))
y = int(input("Enter a Second Number : "))
gcd = find_gcd(x, y)
print("GCD of two numbers is : ", gcd)




OUTPUT
=============

Enter a First Number : 5
Enter a Second Number : 20
GCD of two numbers is :  5




OUTPUT
=============

Enter a First Number : 23
Enter a Second Number : 45
GCD of two numbers is :  1




OUTPUT
==============

Enter a First Number : 56
Enter a Second Number : 90
GCD of two numbers is :  2




Conclusion
=============

Try running the above program and provide the random numbers and note down the results.

Post a Comment

0 Comments