I have some problems with a programing exercise, I am doing a function to found the divisors of a number like is show in https://es.wikipedia.org/wiki/M%C3%A1ximo_com%C3%BAn_divisor, the question is
Why if i execute:
print (div_comun_divisor(60))
I get:
([60, 30.0, 15.0, 5.0, 1.0], [2, 2, 3, 5])
But if i execute both lines:
print (div_comun_divisor(40))
print (div_comun_divisor(60))
I got
([40, 20.0, 10.0, 5.0, 1.0], [2, 2, 2, 5])
([40, 20.0, 10.0, 5.0,1.0, 30.0, 15.0, 5.0, 1.0], [2, 2, 2, 5, 2, 2, 3, 5])
I can observe, that the first execution return correctly, but the second one takes the value of the first execution and then continue writing over the first values.
Here is the code:
def primos(limite):
primos = []
for numero in range(2, int(limite) + 1 ):
if es_primo(numero):
primos.append(numero)
return primos
def es_primo(numero):
for i in range(2,numero):
if (numero % int(i))==0:
# es divisible
return False
return True
def div_comun_divisor(resto, divisores = [], candidatos = []):
lisprimos = primos(resto)
if len(divisores) == 0:
#import pdb; pdb.set_trace()
divisores.append(resto)
for primo in lisprimos:
resto_antes = resto
resto = resto / primo
residuo = resto_antes % primo
if (residuo == 0 and resto > 0):
divisores.append(resto)
candidatos.append(primo)
break;
else:
resto = resto_antes
if(divisores[-1] == 1):
return (divisores, candidatos)
else:
return div_comun_divisor(divisores[-1], divisores, candidatos)
#print (primos(20))
#print (div_comun_divisor(40))
print (div_comun_divisor(60))
Could you help me checking is a bug in the interpeter. Thanks a lot.