The greatest common divisor, also known as GCD, is the greatest number that will, without a remainder, fully divide a pair of integers.
Now, I want you to make a program that will accept two integers and with the use of loops, print out their GCD. Make good use of conditional statements as well.
Off you go!
Input
A line containing two integers separated by a space.
6·9
Output
A line containing an integer.
3
SOLUTION FOR THE ABOVE QUESTION
SOLUTION CODE
#define the function to find the gcd of two numbers
def GCD_function(first_number, second_number):
# define the if condition
if first_number > second_number:
temp = second_number
else:
temp = first_number
for j in range(1, temp + 1):
if (( first_number % j == 0) and (second_number % j == 0 )):
gcd = j
return gcd
first_number, second_number = input("\nEnter two numbers to find their GCD separated by space: ").split(" ")
first_number = int(first_number)
second_number = int(second_number)
# call the gcd_fun() to find the result
gcd = GCD_function(first_number, second_number)
print("\nGCD of "+str(first_number)+" and "+str(second_number)+" is "+str(gcd))
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment