Function that returns the smallest prime number in Python
Was writing Python code that would receive a number and return the first prime number less than or equal to that number.
I created a function called maior_primo
, which does the following:
-
maior_primo(100)
- returns 97. -
maior_primo(23)
- returns 23.
The code works, but I think it got too big as I had to create two other additional functions, can someone show me a simpler way to do this? The code follows below:
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
4
Author: Luiz Felipe, 2017-03-19
2 answers
For the function maior_primo
, 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
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
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
5
Author: Miguel, 2017-10-17 16:25:29
Using while (without generating expression):
def maior_primo(num):
while num > 2:
i = 2
while True:
if num % i == 0:
break
if i == num - 1:
return num
i = i + 1
num = num - 1
Using for (without generating expression):
def maior_primo(num):
for n in range(num, 2, -1):
for i in range(2, n):
if n % i == 0:
break
if i == n - 1:
return n
Using generating expression:
def maior_primo(num):
return max( n for n in range(num, 2, -1) if all(n % i!=0 for i in range(2, n)) )
List:
def lst_primos(num):
primos = [2]
i = 3
for _ in range(2, num):
if all(i % p != 0 for p in primos):
primos.append(i)
i += 1
return primos
1
Author: danbros, 2019-07-30 07:26:31