Program to find MMC in Python

0

I was doing a basic exercise for the While function, it asked to create a program that found the MMC between 2 numbers ... I could do it, but the program continues to print the answer non-stop in loop . Where did I go wrong?

num1 = int(input("Digite um número inteiro:"))
num2 = int(input("Digite outro número inteiro:"))

if num1 > num2:
    maior = num1
else:
    maior = num2
while True:
    if maior % num1 == 0 and maior % num2 == 0:
        print(maior)
    else:
        maior += 1
    
asked by anonymous 14.09.2017 / 01:43

4 answers

2

You can simply add a break after printing your "greater" variable, so it will interoperate with the while. This way:

num1 = int(input("Digite um número inteiro:"))
num2 = int(input("Digite outro número inteiro:"))

if num1 > num2:
    maior = num1
else:
    maior = num2
while True:
    if maior % num1 == 0 and maior % num2 == 0:
        print(maior)
        break
    else:
        maior += 1

I hope I have helped.

EDIT: As you said you have not yet seen break try doing so with a for loop that will leave your code even cleaner.

num1 = int(input("Digite um número inteiro:"))
num2 = int(input("Digite outro número inteiro:"))

if num1 > num2:
    maior = num1
else:
    maior = num2

for i in range(maior):
    aux = num1 * i
    if (aux % num2) == 0:
        mmc = aux

print(mmc)

I hope to have helped my friend.

    
14.09.2017 / 01:58
3

Now a lazy and inefficient version: calculate the common multiples in [a..a * b] and select the first one ...

[x for x in range(a,a*b+1) if x%b==0 and x%a==0][0]
    
14.09.2017 / 15:06
2

I think this code is wrong, but if it is to do so, then do it this way:

num1 = int(input("Digite um número inteiro:"))
num2 = int(input("Digite outro número inteiro:"))
maior = num1 if num1 > num2 else num2
while maior % num1 != 0 or maior % num2 != 0:
    maior += 1
print(maior)
    
14.09.2017 / 02:15
2

Hello,

Actually what was causing this loop was the condition while True: so there is no parameter telling Python that this condition could be false and will always roll the script. Here's an example here without the use of break I hope it serves your purpose:

#Função mmc
def calcular_mmc(num1, num2):
    mdc = num1
    y = num2

    resto = None
    while resto is not 0:
        resto = mdc % y
        mdc  = y
        y  = resto

    return (num1 * num2) / mdc


#passando os parametros para o metodo mmc() fazer os calculos
resp = calcular_mmc(x, y)
print("Resultado: "+str(resp))
    
14.09.2017 / 02:32