Determine the largest prime number after being given a value using while function [duplicate]

0

I have to create an exercise to find the largest prime number after being given a certain value using the while function, what is wrong with 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      
    
asked by anonymous 07.07.2017 / 16:36

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 one more element in:

while y<=n:
    y=y+1

To know if a number is prime we have to try to divide by all that are in the middle and not only one, as it 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
    
07.07.2017 / 17:34