DEV Community

Poornima Ravi
Poornima Ravi

Posted on

LCM & GCD of two numbers

#LCM of two numbers
Num1 = int(input('Enter the Number 1:'))
Num2 = int(input('Enter the Number 2:'))
def evaluateN(Num1,Num2):
    if Num1>Num2:
        N= Num1
    else:
        N= Num2  
    return N
LCM = 1
i = 2
N = evaluateN(Num1,Num2)
if Num1>1 or Num2>1: 
    print(Num1,Num2)
    while i<=N:
        if Num1%i ==0 and Num2%i ==0:
            Num1 = Num1//i
            Num2 = Num2//i
            LCM = LCM * i
            print('i:',i, '|',Num1,Num2)
            i=2
        elif Num1%i ==0 and Num2%i !=0:
            Num1 = Num1//i
            LCM = LCM * i
            print('i:',i,'|', Num1,Num2)
            i=2
        elif Num1%i !=0 and Num2%i ==0:
            Num2 = Num2//i
            LCM = LCM * i
            print('i:',i,'|', Num1,Num2)
            i=2
        else:
            i+=1   
        N = evaluateN(Num1,Num2)   
    print('LCM :', LCM)
elif Num1==Num2:
    print('LCM :',LCM)
else:
    print('Enter Valid Num')



#GCD of two Numbers
Num1 = int(input('Enter the Number 1:'))
Num2 = int(input('Enter the Number 2:'))
def evaluateN(Num1,Num2):
    if Num1>Num2:
        N= Num1
    else:
        N= Num2  
    return N
GCD = 1
i = 2
N = evaluateN(Num1,Num2)
if Num1>1 or Num2>1: 
    print(Num1,Num2)
    while i<=N:
        if Num1%i ==0 and Num2%i ==0:
            Num1 = Num1//i
            Num2 = Num2//i
            GCD = GCD * i
            print('i:',i, '|',Num1,Num2)
            i=2
        else:
            i+=1   
        N = evaluateN(Num1,Num2)   
    print('GCD:', GCD)
elif Num1==Num2:
    print('GCD:',GCD)
else:
    print('Enter Valid Num')

Enter fullscreen mode Exit fullscreen mode

Top comments (0)