[英]Improve code to find prime numbers
I wrote this python code about 3 days ago, and I am stuck here, I think it could be better, but I don't know how to improve it. 我大约三天前写了这个python代码,我被困在这里,我认为它可能会更好,但是我不知道如何改进它。 Can you guys please help me? 你们能帮我吗?
# Function
def is_prime(n):
if n == 2 or n == 3:
return True
for d in range(3, int(n**0.5), 2):
if n % d == 0:
return False
return True
A good deterministic way to find relatively small prime numbers is to use a sieve . 确定相对较小质数的一种好的确定性方法是使用筛子 。
The mathematical principle behind this technique is the following: to check if a number is prime, it is sufficient to check that it is not divisible by other primes. 该技术背后的数学原理如下:检查一个数字是否为质数,足以检查它是否可以被其他质数整除。
import math
def is_prime(n):
# Prepare our Sieve, for readability we make index match the number by adding 0 and 1
primes = [False] * 2 + [True] * (n - 1)
# Remove non-primes
for x in range(2, int(math.sqrt(n) + 1)):
if primes[x]:
primes[2*x::x] = [False] * (n // x - 1)
return primes[n]
# Or use the following to return all primes:
# return {x for x, is_prime in enumerate(primes) if is_prime}
print(is_prime(13)) # True
For reusability your could adapt the above code to return the set
of all prime numbers up to n
. 为了实现可重用性,您可以修改上面的代码以返回最大为n
的所有素数的set
。
Try the below code, the speed of it is the same as Olivier Melançon's solution: 尝试以下代码,其速度与OlivierMelançon的解决方案相同:
from math import sqrt; from itertools import count, islice
def is_prime(n):
return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
print(is_prime(5))
Output: 输出:
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.