如何改善关于欧拉问题7的代码

时间:2019-05-11 20:31:41

标签: python python-3.x optimization primes

我已经开始学习python,做了一些基本的工作之后,我开始做欧拉问题。我能够做到7,但编译需要很长时间。有人可以帮我吗?

这是我编写的唯一代码

def prime(n):
    count = 0
    if n <= 1:
        print("Number is neither prime nor composite")
    if n == 2:
        print("Number is prime")
    if n > 2:
        for i in range(2, n//2 + 1):
            if n % i == 0:
                count += 1
            else:
                count += 0
    if count == 0:
        return True
    else: 
        return False


b = 10001
a = []
i = 2
while len(a) < b:
    if prime(i):
        a.append(i)
        i += 1
    else:
        i += 1
print(a[-1])

3 个答案:

答案 0 :(得分:1)

无需查找数字的所有因素。找到因子后,数字显然不是质数,您可以立即返回False

编辑:
正如Federico Domeniconi在评论中提到的那样,也无需迭代n的一半。迭代到其平方根就足够了:

if n > 2:
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False

    # No factors found, n is a prime:
    return True

答案 1 :(得分:0)

如果您真的想把这种解决方案归结为:

def is_prime(n):
    factors = range(2, int(math.sqrt(n)) + 1)
    return (n > 1 and all(n % f for f in factors))

一个我可能曾经知道却忘记了的意外琐事。为什么函数为True返回n = 2

factors # range(2, 1 + 1)
        # range(2, 2)
        # Which is an empty range.
        # Or in more concrete form: an empty list.

n > 1   # True
all([]) # Hmmmmm?
        #
        # Are all of the items in an empty collection true?
        #
        # If every tree falls in the forest at once, but no one hears them,
        # does it make a sonic boom?
        #
        # Contrary to Billy Preston -- and microeconomists world wide --
        # can you really get something from nothing?
        #
        # Python says YES. I'm sure smart mathematics do too, but
        # I would be curious to hear the reasoning.

我想我的问题中有Stack answer。逻辑学家对此有一个name:“ 虚假事实是断言空集合的所有成员都具有特定属性的声明。”

答案 2 :(得分:0)

如果您正在解决欧拉计划中的问题,那么最好拥有自己的Sieve of Eratosthenes。这样可以快速计算素数非常,比您当前使用的方法分解试验快得多。您会发现它对于他们的许多问题很有用。

欧拉7的解决方案变为:

  1. 使用Prime Number Theorem估算第10,001个素数的大小。

  2. 运行Eratosthenes筛至第1步的极限,为安全起见要超出极限。

  3. 对筛子的输出进行计数以找到第10,001个素数。

相关问题