Exercicio calculo maior numero python

Asked

Viewed 1,927 times

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))

1 answer

2


in your check from 1 to 1, you are looking for splitters up to the given maximum number(k), not up to the smallest number you are checking (n):

if all(n%x!=0 for x in range(2,k)):

Exchange for:

if all(n%x!=0 for x in range(2,n)):

and should work.

After tidying up, there is a little space for you to optimize the thing: why start looking for the primes from the lowest number, for example? Would it have any gain if you started from K and were checking the progressively smaller numbers?

Also see if you understand what this line that you need to fix is doing - it’s much more advanced code than the code that you have around - if you don’t understand, it’s nicer to rewrite in a simpler way, than using a magic formula that "more or less works".

  • 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?

  • 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.

  • I didn’t know that directive all() with this list understanding. Python always amazes me with its elegance

Browser other questions tagged

You are not signed in. Login or sign up in order to post.