Project Euler # 10 with Python, summing Numpy sums wrong

Project Euler # 10

I know that this question has been asked, but it’s hard for me to understand why I get the wrong answer, and other messages about it did not help me. The code is to find the sum of primes below 2,000,000.

import math
import numpy as np

def sum_primes(limit):      
    potential = 2
    primes = [potential]
    potential += 1
    primes.append(potential)

    while potential < limit:
        potential+=2
        test = True
        sqrt_potential = math.sqrt(potential)
        for a in primes:
            if a > sqrt_potential:
                break
            if potential%a == 0:
                test = False
                break
        if test and potential <= limit:
            primes.append(potential)

    print np.sum(primes)
    return

It seems like I am pushing all prime numbers, but for some reason the sum is not working out correctly. Does anyone see a problem here?

Here is the result I get:

>>> sum_primes(20000)
21171191
>>> sum_primes(200000)
1709600813
>>> sum_primes(2000000)
1179908154
+4
source share
2 answers

I gave a rather naive implementation, the last iteration took time to return the results.

def return_primes(upto=100):
    primes = []
    for i in range(2, upto+1):
        if not any(not i % p for p in primes):
            primes.append(i)
    return primes

And use:

>>> sum(return_primes(upto=20000))
21171191
>>> sum(return_primes(upto=200000))
1709600813
>>> sum(return_primes(upto=2000000))
142913828922

Here's another implementation using the Sieve of Eratosthenes:

def return_primes(upto=100):
    primes = []
    sieve = set()
    for i in range(2, upto+1):
        if i not in sieve:
            primes.append(i)
            sieve.update(range(i, upto+1, i))
    return primes

, , :

>>> sum(return_primes(200000))
1709600813
>>> sum(return_primes(2000000))
142913828922

, ,

>>> 142913828922 % 2**32
1179908154

( Will Ness) , 32- . :

import math
import numpy as np

def sum_primes(limit):      
    potential = 2
    primes = [potential]
    potential += 1
    primes.append(potential)
    while potential < limit:
        potential+=2
        test = True
        sqrt_potential = math.sqrt(potential)
        for a in primes:
            if a > sqrt_potential:
                break
            if potential%a == 0:
                test = False
                break
        if test and potential <= limit:
            primes.append(potential)
    print np.sum(primes, dtype=np.int64)
    return

.

, :

    print np.sum(primes, dtype=np.int32)
+2

script potential = 3. while 5. 3 . , potential -= 1 script.

:

def sumPrimes(n):
    b, p, sum = [True] * (n+1), 2, 0
    for p in xrange(2, n+1):
        if b[p]:
            sum += p
            for i in xrange(p, n+1, p):
                b[i] = False
    return sum

Project Euler, " Prime" .

+2

Source: https://habr.com/ru/post/1531625/


All Articles