Determine the largest prime number after a value is given using while function

Asked

Viewed 978 times

0

I have to create an exercise to discover the largest prime number after being provided me a certain value using the while function, which is wrong in what I created below??

def maior_primo(n):
    x=0
    y=0
    while y<=n:
        y=y+1
        x=n-1
        if (x % y==0 and x//y==0):
            return x
        else:
            x%y!=0
            return y      
  • 1

    And you want us to guess what the language is?

  • 1

    Python by syntax

  • 1

    This does not eliminate the use of xD tags

  • Sure, it was just a guess :D

1 answer

0

There are some problems with your solution. The increment in the cycle was being done right at the beginning so I would analyze an extra element, in:

while y<=n:
    y=y+1

To know if a number is prime we have to try to divide by all who are in the middle and not just one, as happens here:

if (x % y==0 and x//y==0):
    return x

Extending your solution and making it right:

def maior_primo(n):
    x=0
    y=n #começar do cima para baixo para poder sair no primeiro primo

    while y>=1: #ciclo agora ao contrario até 1
        for x in range(2, y + 1): #range nao inclui o ultimo, logo tem de ser y +1
            if y % x == 0:
                break

        if x == y: #se chegou até y é porque nao deu para dividir por nenhum, logo primo
            return x

        y = y - 1

    return 1 #se nao deu para achar nenhum primo retorna-se um

Browser other questions tagged

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