Function that returns the smallest prime number. In PYTHON

2

Greetings, I was writing a Python code that received a number, and returned the first prime number less than or equal to that number.

So (I created a function called "major_primo"), which does the following:

largest_primo (100) - returns 97 highest_primo (23) - returns 23

The code works, but I think it got really big because I needed to create two additional functions, can someone show me a simpler way to do this? The code is as follows:

def primos_maiores_que_10(n):

    i=2
    while i<10:
        if(n%i==0):
            return "Não é primo."
        i=i+1
    return 1

def primos_menores_que_10(n):
    if n==2 or n==3 or n==5 or n==7:
        return 1
    else:
        return "Não é primo."


def maior_primo(n):
    x=0
    while n<2:
        n=int(input("Digite o valor de n>= 2."))

    while n>1:
        if n>10:
            x=primos_maiores_que_10(n)
            if x==1:
                return n
            n=n-1
        else:
            x=primos_menores_que_10(n)
            if x==1:
                return n
            n=n-1
    
asked by anonymous 19.03.2017 / 13:37

1 answer

2

Regarding the maior_primo function, you can rewrite it to the following:

def maior_primo(n):
    for num in reversed(range(1,n+1)):
        if all(num%i!=0 for i in range(2,num)):
            return num

n=int(input("Digite o valor de n>= 2.")) # 100
print(maior_primo(n)) # 97

DEMONSTRATION

With while:

def maior_primo(n):
    while n > 0:
        if all(n%j!=0 for j in range(2,n)):
            return n
        n -= 1

n=int(input("Digite o valor de n>= 2.")) # 100
print(maior_primo(n)) # 97

DEMONSTRATION

As for the others we can make a change to the program completely, to become more flexible reusable / scalable:

def e_primo(num): 
    return all(num%i!=0 for i in range(2,num)) 

def primos_menores_que_n(n, start=1):
    for num in range(start,n):
        if e_primo(num):
            yield num    

def maior_primo(n):
    for num in reversed(range(1,n+1)):
        if e_primo(num):
            return num

def primos_maiores_que_n(n, lim):
    return primos_menores_que_n(lim, start=n)

print(list(primos_menores_que_n(10))) # [1, 2, 3, 5, 7]
print(list(primos_maiores_que_n(10, 30))) # [11, 13, 17, 19, 23, 29]
print(maior_primo(100)) # 97
print(e_primo(10)) # False
print(e_primo(11)) # True

DEMONSTRATION

    
19.03.2017 / 14:38