简体   繁体   English

如何加快寻找过程?

[英]How to speed up the prime-finding process?

I was doing Problem 7 on Project Euler when I ran into a problem. 当我遇到问题时,我在项目Euler上做了问题7。 My code was taking to long to finish. 我的代码需要很长时间才能完成。 Here is my code. 这是我的代码。

def Problem7():
    num = 0
    p = 0 
    while p < 10002 :
        prime = True
        for i in range(2,num):
            if (num%i==0):
                prime = False
        if prime:
           print(num)
           p = p + 1
        num = num + 1
Problem7()

How do I make it faster? 如何让它更快? Is there another way? 还有另外一种方法吗?

You should make your life easier and print the prime count at the end which is what I suspect the p variable is storing. 你应该让你的生活更轻松,并在最后打印素数,这是我怀疑p变量存储的。

As noted in comments, you can eliminate a lot of calculations with a smarter algorithm. 如评论中所述,您可以使用更智能的算法消除大量计算。

1: Check if the number is even (num%2) (if so, not prime) 1:检查数字是否为偶数(num%2)(如果是,不是素数)

2: While divisor is less than or equal to square root and prime ==True, test divisor 2:当除数小于或等于平方根且prime == True时,测试除数

3: If still not prime, increment by 2 so you only test odd numbers (All evens were checked with num%2) 3:如果仍然不是素数,则增加2,这样你只测试奇数(所有均值都用num%2检查)

If you wanted to get super efficient, every number that is not prime has at least one prime factor, so you could store each prime that you find in an array and only check those up to the highest in the array... But that is a lot of extra coding that is not necessary to this problem. 如果你想要超高效,那么每个非素数都至少有一个素数因子,所以你可以存储你在数组中找到的每个素数,并且只检查数组中最高的那些......但那是这个问题不需要很多额外的编码。 Using the above logic I've found the first 10,000 primes in a matter of a few seconds on a test run. 使用上面的逻辑,我在测试运行的几秒钟内找到了前10,000个素数。

If you think of the number 100, your logic tests 99 possible divisors. 如果你想到数字100,你的逻辑测试99可能的除数。 The above logic tests only 2 then stops. 上面的逻辑测试只有2然后停止。 Worst case of going to the square root would be only 2,3,5,7,9... 5 calculations instead of 99. 最糟糕的情况是去平方根只有2,3,5,7,9 ... 5计算而不是99。

I used the following method to check if number is prime (runs in 0m0.612s): 我使用以下方法检查数字是否为素数(在0m0.612s中运行):

import math

def is_prime(num):
    if num == 0 or num == 1:
        return False
    if num == 2:
        return True
    temp = 2
    while temp < math.sqrt(num) + 1:
        if num % temp == 0:
            return False
        temp += 1

    return True

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

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