Search code examples
pythonfor-loopident

Maximum common divider for two numbers on Python


I need help to check a little code:

def mcd(n1,n2):
  mxcd = 0
  for i in range(1,n1):  
    f = n1 % i  
    for j in range(1,n2):
      g = n2 % j 
      if (f == 0 and g == 0 and f == g): 
        mxcd = f  
      else: 
        mxcd = "No hay comun divisor"
  return mxcd 

I have problems because it seems it never enters the first if, It always enters the else, I've tried changing the indentation orders, taking out the if from the second for but it's not working. If someone could help that would be great.


Solution

  • Your if statement logic is off.

    You want:

    if (f==0 and g==0 and i==j):
        mxcd = i
    

    Do you see why that is?

    There are several other things wrong with this function but that’s why the if isn’t working.