简体   繁体   中英

Python is taking a very long time to execute code

I'm using PyCharm community 2018. I'm trying to find the sum of prime numbers from 1 to two million and this is my code.

primes = [x for x in range (1,2000000) if all (x%y!=0 for y in range (2,x))]
total = 0
for x in primes:
    total = total + x
print (total)

It's been 20 minutes and I've still got no output. Do you have any suggestions to make it run faster or is my method wrong?

This is most likely because your method to find primes is inefficient and your range is too large.

Your algorithm is a brute force way of finding prime numbers and it's time complexity is O(n²). If you time your algorithm for smaller numbers you will see that as you increase n , time taken does not increase linearly, but is in fact quadratic.

+--------+---------------+
|   n    | time(in sec)  |
+--------+---------------+
| 1000   |  0.007979     |
| 2000   |  0.038865     |
| 5000   |  0.137037     |
| 10000  |  0.499688     |
| 20000  |  1.892315     |
| 50000  |  10.29843     |
| 100000 |  1374.101     |
| ...    |  ...          |
+--------+---------------+

I would suggest you to take a look at Sieve of Eratosthenes . You will find many implementations of it in whichever language you want if you search for this.

I'd recommend using multiprocessing to speed up your code

from multiprocessing import Pool
def find_prime(n):
    #code to determine prime number here
    #return 0 if it is not prime or the number if it is

pool=Pool()
total=sum(pool.map(find_prime,range(1,2000000))

Your code is correct. There are lots of ways to get all prime numbers and you are using the most basic definition, and that's why your code is slow. You can refer to this post (There are lots of ways to get all prime numbers and you are using the most basic definition, and that's why your code is slow. You can refer to this post Fastest way to list all primes below N to ) for more advanced and efficient ways to calculate prime numbers and that should speed up your code a lot. Though you will need to learn and understand lots of mathematical principles and details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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