Python prime numbers | while

Asked

Viewed 6,285 times

0

I have the following problem:

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) must return 97

maior_primo(7) must return 7

Tip: write a function éPrimo(k) and loop through the numbers to the given number checking whether the number is prime or not; if so, store in a variable. At the end of the loop, the value stored in the variable is the largest prime found.

My solution would be:

def éPrimo (k):
    div = 2
    while k % div != 0 and div <= k:   
        div = div + 1
        if k % div == 0:
            k = k - 1
        else:
            print (k)

I am very much convinced that I am right, I am still at a very beginner level and if someone can give me a light on these basic parameters it would be of great help.

1 answer

2

def ehPrimo(x):
    if x >= 2:
        for y in range( 2, x ):
            if not ( x % y ):
                return False
    else:
        return False

    return True

num = int(input("Entre com um numero: "))

for n in range( num, 0, -1 ):
    if ehPrimo(n) :
        print n
        break

Browser other questions tagged

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