Calculation exercise largest number python

0

Good afternoon,

I'm developing an exercise in python , I saw that there are already some similar resolutions in the forum, but I have developed one myself and I do not understand the reason for the malfunction (only 0 is returned, be that it falls into if <2 , in which case the answer is "ERROR")

Follow the code and proposal of the exercise, thank you for the help.

Write the largest_primo function that receives an integer greater than or equal to 2 as a parameter and returns the largest prime number less than or equal to the number passed to the

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))
    
asked by anonymous 09.01.2018 / 21:22

1 answer

1

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

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

Switch By:

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 cousins from the lowest number, for example? Would it have any gain if you started from K and checked the progressively smaller numbers?

Also see if you understand correctly what this line that needs correction is doing - it's code far more advanced than the code you have around - if you're not understanding, it's cool to re-write in a way simpler, you understand, than using a magic formula that "more or less works".

    
09.01.2018 / 22:47