Given two positive numbers m and n find their GCD.

Input 1:

14
21

Output 1: 7

Input 2:

15
8

Output 2: 1

Python GCD

# Read the two inputs
m = int(input())
n = int(input())

# Initialise a variable temp to minimum of m and n
temp = min(m,n)

# Initialise a variable gcd to 1. This will contain the final gcd value. We have
# assigned it to 1 because that is the lowest value possible by default
gcd = 1

# Run a loop till temp, i.e. the minimum of the two numbers
for i in range(1,temp+1):

# If 'i' is divisible by both m and n, update the gcd to i    
    if m%i==0 and n%i==0:
        gcd = i

# Print the final value of gcd        
print(gcd)      


# Alternative, more efficient solution. This uses the Euclidean Algorithm the link
# to which is given below:
#https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/

# Run a loop till one of m or n aren't zero
while(m != 0 and n != 0):

# If m>n, take the modulo of m against n    
    if(m > n):
        m = m % n
# Alternatively, if n>m, take the modulo of n against m        
    else:
        n = n % m
 
# Print whichever one of them isn't zero    
if(m != 0):
    print(m)
else:
    print(n)

Comments