How to speed up the search process?

I performed task 7 in Project Euler when I came across a problem. My code lasted a long time. 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 to make it faster? Is there another way?

+4
source share
2 answers

You should make your life easier and print a hit counter at the end, which I suspect the variable p stores.

As noted in the comments, you can eliminate a lot of calculations using a more reasonable algorithm.

1: check if the number is even (num% 2) (if so, not just)

2: While the divisor is less than or equal to the square root, and prime = True, the test divisor

3: , 2, ( num% 2)

, , , , , , ... , . , 10000 .

100, 99 . 2 . 2,3,5,7,9... 5 99.

+3

, , ( 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
+1

All Articles