如何找到给定范围内的所有素数?

时间:2012-11-17 05:08:49

标签: python-3.x

def all primes(start,end):
    list_primes = []
    for i in range(start,end):
        for a in range(2,i):
            if i % a == 0:
                list_primes.append(i)

    return list_primes

由于某种原因,它会返回除素数之外的所有内容。这可能是一些愚蠢的错误。有人可以帮忙吗?

6 个答案:

答案 0 :(得分:1)

将内循环更改为:

for a in range(2,i):
    if i % a == 0:
        break
else:
    list_primes.append(i)

here粘贴的复制品:-)
顺便提一下,他们使用相同的代码,例如:)

答案 1 :(得分:1)

试试这个(使用Sieve of Eratosthenes):

    def all_primes(start, end):
        return list(sorted(set(range(start,end+1)).difference(set((p * f) for p in range(2, int(end ** 0.5) + 2) for f in range(2, (end/p) + 1)))))

答案 2 :(得分:1)

要获得素数,请尝试实施Sierat of Eratosthenes算法https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

在Python 3中寻找100万个数字,我需要大约0.5秒

def get_primes(start, stop):
    dct = {x: True for x in list(range(start, stop+1))}
    x = start

    while x ** 2 <= stop:
        if dct[x]:
            y = x ** 2
            while y <= stop:
                dct[y] = False
                y += x
        x += 1

    lst = []
    for x, y in dct.items():
        if y:
            lst.append(x)

    return lst

res = get_primes(2, 1000000)
print(res)

答案 3 :(得分:1)

我想分享一下,我发现在一个范围内生成质数的最快方法是使用SymPy symbolic mathematics library

import sympy 

def all_primes(start, end):
    return list(sympy.sieve.primerange(start, end))

sympy.sieve.primerange()函数返回一个生成器,因此我们需要list()将其转换为列表。

以下是此广告与此线程中目前最受欢迎的已经非常优化的答案之间的性能差异示例:

import sympy

def get_primes_python(start, stop):
    dct = {x: True for x in list(range(start, stop+1))}
    x = start

    while x ** 2 <= stop:
        if dct[x]:
            y = x ** 2
            while y <= stop:
                dct[y] = False
                y += x
        x += 1

    lst = []
    for x, y in dct.items():
        if y:
            lst.append(x)

    return lst

def get_primes_sympy(start, stop):
    return list(sympy.sieve.primerange(start, stop))
In [2]: %timeit test.get_primes_python(1, 10**7)
1 loop, best of 3: 4.21 s per loop

In [3]: %timeit test.get_primes_sympy(1, 10**7)
10 loops, best of 3: 138 ms per loop

答案 4 :(得分:0)

你可以尝试这个功能

def generate_primes(lower_limit,upper_limit):
    if not isprime(lower_limit):
        return False
    candidate = lower_limit
    r = []
    while(candidate <= upper_limit):
        trial_divisor = 2
        prime = 1 # assume it's prime
        while(trial_divisor**2 <= candidate and prime):
            if(candidate%trial_divisor == 0):
                prime = 0 # it isn't prime
            trial_divisor+=1
        if(prime):
            r += [candidate]
        candidate += 2
    return r

def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2: 
        return True    
    # all other even numbers are not primes
    if not n & 1: 
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

我在此页http://dunningrb.wordpress.com/2009/02/12/prime-numbers-and-a-simple-python-code/

中对其进行了修改

答案 5 :(得分:0)

试试这个:

def isprime (x):
    isprime=True
    if x!=2:
        for i in range (2,x):
            if x%2==0:
                isprime=False
            break
        return isprime
x=int(input("enter a number"))
z=isprime(x)
print(z)