Problem: While the following code works, it takes far too long to be of any use in finding the sum of all primes below the number 2,000,000.
Past attempts: I've attempted implementing while loops, counters, and a number of other tools to modify the code, but they end up modifying my results as well. Previously, I'd simply added the numbers to an existing variable instead of appending them to a list, but the result was the same.
I believe that a generator function/expression will solve the problem, but I've had trouble implementing either the function, expression, or both.
# Prime number determiner
def is_prime(x):
for i in range(2, x-1):
if x % i == 0:
return False
else:
return True
# Function summing all prime numbers between 2 and 2,000,000
for i in range(2, 2000000):
if is_prime(i) is True:
primes.append(i)
results = sum(primes)
print(primes)
Previous attempt at generator expressions/functions:
#Generator version of above
def is_prime_gen(x):
yield (i for i in range(2, x-1) if x % i == 0)
sum_prime += (j for j in range(2, 2000000) if is_prime_gen(j))
Expected results: I don't need the result to process super-fast, but I would like it to process within a minute or two.
Bonus: For anyone responding, it would be helpful to me if you could also explain how you came to your conclusions (and while "experience" is a valid explanation, it isn't a helpful).