Home >Backend Development >Python Tutorial >LCM & GCD of two numbers

LCM & GCD of two numbers

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 06:05:11149browse

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')

The above is the detailed content of LCM & GCD of two numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn