How to calculate the MCM in python?

1

I am learning is my first semester and I have the task of calculating the MCM in Python but in my code I get an error and I do not know how to fix it could someone tell me how to fix my code?

A =int(input())
B =int(input())
C = B

while(C!= 0):
    C= A%B
    A = B
    B = C 
    X = (A*B)/B
print(X)
    
asked by lalo hernandez 10.12.2016 в 23:06
source

1 answer

6

From what I see, I think you're trying to get the GCF (greatest common factor) by using Euclid's algorithm and then use it to calculate the MCM (common multiple multiplo) given that:

  

M.C.M (A, B) = (A * B) / M.C.D (A, B)

As you have your code you get an error by division between 0:

  

ZeroDivisionError: division by zero

since there comes a time when B is 0 and produces an error in the line:

X = (A*B)/B

This line is to calculate the M.C.M using the M.C.D and does not belong therefore to the Euclides algorithm so it should be out of the while loop:

On the other hand, the algorithm requires knowing which is the smallest number, so it is appropriate to check this before and assign each value appropriately. The code could look like this:

num1 =int(input())
num2 =int(input())

A = max(num1, num2)
B = min(num1, num2)

while B:
    mcd = B
    B = A % B
    A = mcd
mcm =  (num1 * num2) // mcd

print('El M.C,D de {0} y {1} es {2}'.format(num1, num2, mcd))
print('El M.C.D de {0} y {1} es {2}'.format(num1, num2, mcm))

This would be an example of execution:

54
90
El M.C,D de 54 y 90 es 18
El M.C.D de 54 y 90 es 270

min () and max () are two Python prebuilt functions that return the minimum and maximum value of an iterable respectively, if you do not want to use them you can substitute those two lines for something like :

if num1 > num2:
    A = num1
    B = num2
else:
    A = num2
    B = num1

Clarification : Since you do not specify which version of Python you use, I used the entire division // and not / when calculating the MCM using the MCD because in Python 3 / returns a float and not a int as in Python 2.

    
answered by 11.12.2016 / 00:01
source