Can this Greatest Common Divisor Program be solved in a simpler way?

36 Views Asked by At

Code:

def g(x , y):
    mod = 1
    while(mod!=0):
        mod = y % x
        g = x
        y = x
        x = mod
    return g
x = int(input("x: "))
y = int(input("y: "))
print(g(x , y)) 

Program to find the greatest common divisor in python.

1

There are 1 best solutions below

0
Yash Mehta On

Code:-

#Euclidean algorithm
def method1(x , y):
    while(y):
       x, y = y, x % y
    return abs(x)
    
#math.gcd() function
import math
def method2(x,y):
    return math.gcd(x,y)
x = int(input("x: "))
y = int(input("y: "))

# Product of numbers = HCF*LCM      i.e [x*y=hcf(x,y)*lcm(x,y)] This only works for two numbers..!
#The lcm function was newly introduced in the Python version 3.9.0.
import math
def method3(x,y):
    return x*y/math.lcm(x,y)
    
print(method1(x,y))
print(method2(x,y))
print(method3(x,y))

Output:-

x: 32
y: 48
16
16
16