简体   繁体   English

Python素数函数填充列表

[英]Python prime number function populating list

so I can do this a simpler way, but I'm practicing with Pure Functions involving lists and I can't get this to work. 所以我可以用一种更简单的方法来做到这一点,但是我正在使用涉及列表的Pure Functions进行练习,因此无法正常工作。 I know i'm cheating and making it nonexact by not mentioning things like excluding 1 and not saving processesing time by only tabulating odd numbers but that's not my focus here. 我知道我在欺骗并使其变得不精确,因为它没有提到诸如排除1之类的事情,并且仅通过列表奇数来节省处理时间,但这不是我的重点。 Pointers? 指针?

def is_prime(n):
    for i in range(2, n+1):
        if n % i == 0:
            return False
    return True

def listprimes_upto(n):
    result = []
    for i in range(2, n):
        if is_prime(i):
            result.append(i)
    return result

print(listprimes_upto(50))

(here's the easier non-list version that works fine): (这是较简单的非列表版本,可以正常运行):

def listprimesupto(n):
    for p in range(2, n+1):
        for i in range(2, p):
            if p % i ==0:
                break
        else:
            print(p)  

listprimesupto(50)

Your is_prime is wrong. 您的is_prime错误。 You must use range(2,n) , otherwise you will always get False from the function. 您必须使用range(2,n) ,否则将始终从该函数获得False Because, obviously, the last i in the range will be n and n % i == 0 . 因为,显然,范围中的最后一个i将为nn % i == 0

def is_prime(n):
    #                vvv n here, not n+1
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

Try this, 10x times efficient than your code when you use big numbers. 尝试使用此方法,效率比使用大数字时的代码高10倍。

def is_prime(n):
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

def listprimes_upto(n):
    result = []
    for i in range(2, n):
        if is_prime(i):
            result.append(i)
    return result

print(listprimes_upto(50))

See Sieve of Eratosthenes - Finding Primes Python 参见Eratosthenes筛-查找Primes Python

The Sieve of Eratosthenes is a much faster approach to finding primes. Eratosthenes筛网是找到质数的更快方法。

this seems to be the fastest solution for finding primes in Python. 似乎是在Python中查找质数的最快解决方案。 There are also many other examples on this page of different ways of implementing functions to find prime numbers, although none of those examples create a second is_prime function leaving that as an exercise for you to figure out. 本页上还有许多其他示例,这些示例以不同的方式实现函数以查找质数,尽管这些示例均未创建第二个is_prime函数,但您可以自己练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM