2
Good afternoon,
I’m developing an exercise in python, I saw that there are already some similar resolutions in the forum, but I developed one of my own and I’m not understanding the reason for the malfunction (only the value 0 is returned, unless I fall in the if <2
, in that case the answer is "ERROR")
It follows code and proposal of the exercise, I thank the help.
Write the maior_prime function that takes an integer number greater than or equal to 2 as parameter and returns the largest prime number less than or equal to the number passed to the function
Note that:
maior_primo(100) deve devolver 97 maior_primo(7) deve devolver 7
def eprimo(k):
n = 2
numero = 0
if k<2:
return "Teste: Não é possivel calcular"
else:
while n<=k:
if all(n%x!=0 for x in range(2,k)):
numero=n
n=n+1
else:
n=n+1
return numero
k=int(input("numero k:"))
print(eprimo(k))
Thank you very much! I made the correction and it worked normally, I understood that if I kept the range between 2 and k it would be much bigger, but still I think that even with this bigger range he should still find the divisions with rest 0 and consequently memorize the number, should not?
– Túlio Maia
the problem with the larger range is that it will go through "n" as well, and the rest of the division n by n is always zero, even if n is prime.
– jsbueno
I didn’t know that directive
all()
with this list understanding. Python always amazes me with its elegance– Jefferson Quesado