Improve code to find prime numbers

蓝咒 提交于 2019-12-11 16:59:38

问题


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. 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

回答1:


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.




回答2:


Try the below code, the speed of it is the same as Olivier Melançon's solution:

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


来源:https://stackoverflow.com/questions/50752438/improve-code-to-find-prime-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!