Write a program to input two numbers as input and compute the greatest common divisor.
def gcd(x, y): gcd = 1 if x % y == 0: return y for k in range(int(y / 2), 0, -1): if x % k == 0 and y % k == 0: gcd = k break return gcd n1 = int(input('n1: ')) n2 = int(input('n2: ')) print("GCD of", n1, '&', n2, 'is', gcd(n1, n2))
Output :
n1: 48
n2: 18
GCD of 48 & 18 is 6
Certainly! The provided Python code defines a function gcd
that calculates the greatest common divisor (GCD) of two numbers using a loop and the Euclidean algorithm. The code also prompts the user to input two numbers and then prints their GCD. Here’s a detailed explanation of how the code works:
Explanation
- Function Definition (
def gcd(x, y):
):
- This line defines a function named
gcd
that takes two parameters,x
andy
, which are the two numbers whose GCD needs to be calculated.
- Check if
y
Dividesx
Exactly (if x % y == 0:
):
- This line checks if
y
is a divisor ofx
. Ifx
moduloy
is 0, theny
is the GCD, and the function returnsy
.
- Loop to Find GCD:
for k in range(int(y / 2), 0, -1): if x % k == 0 and y % k == 0: gcd = k break
- If
y
does not dividex
exactly, the function enters afor
loop. - The loop starts from
int(y / 2)
and goes down to 1. It checks each numberk
to see if it is a common divisor of bothx
andy
. - The first common divisor found (
x % k == 0 and y % k == 0
) is stored ingcd
, and the loop breaks immediately.
- Return GCD:
return gcd
- The function returns the value of
gcd
, which is the greatest common divisor found by the loop.
- Input and Function Call:
- The user is prompted to input two numbers:
python n1 = int(input('n1:')) n2 = int(input('n2:'))
- These inputs are stored in variables
n1
andn2
. - The
gcd
function is called withn1
andn2
as arguments, and the result is printed:python print("GCD of", n1, '&', n2, 'is', gcd(n1, n2))
Example
Let’s go through an example where the user inputs two numbers. Suppose the user inputs the following:
n1: 48 n2: 18
The code execution will be as follows:
- Input Numbers:
n1 = 48 n2 = 18
- Function Call:
gcd(48, 18)
- Check if 18 Divides 48:
48 % 18
is not 0, so the function proceeds to the loop.- Loop to Find GCD:
- The loop starts at
int(18 / 2) = 9
and checks down to 1:- For
k = 9
:48 % 9 != 0
- For
k = 8
:48 % 8 != 0
- For
k = 7
:48 % 7 != 0
- For
k = 6
:48 % 6 == 0
and18 % 6 == 0
, sogcd = 6
and the loop breaks.
- For
- Return and Print Result:
GCD of 48 & 18 is 6
Summary
This code defines a function gcd
to calculate the greatest common divisor of two numbers. It first checks if one number exactly divides the other. If not, it uses a loop to find the highest common divisor by checking divisors from half of the smaller number down to 1. The user is prompted to input two numbers, and the GCD of these numbers is printed.