Maximum common divider for two numbers on Python

698 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

You could start by printing out the state of f and g to see why you don't get anything happening in the if statement.

def mcd(n1,n2):
  mxcd = 0
  for i in range(1,n1):
    f = n1 % i
    print('i is {}, f is {}'.format(i, f))
    for j in range(1,n2):
      g = n2 % j
      print('\n  j is {}, g is {}'.format(j, g))
      if (f == 0 and g == 0 and f == g): 
        mxcd = f  
      else: 
        mxcd = "No hay comun divisor"
  return mxcd 

running something like mcd(2,4) lets you know a lot:

i is 1, f is 0
  j is 1, g is 0  
  j is 2, g is 0    
  j is 3, g is 1
'No hay comun divisor'

You do open the if statement, which you can see by using a similar trick:

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): 
        print('hello')
        mxcd = f  
      else: 
        mxcd = "No hay comun divisor"
  return mxcd 

> mcd(4,8)

hello
hello
hello
hello
hello
hello
'No hay comun divisor'

From there, you have a few issues to correct to get the right answer but I'll leave that exercise to you :)