The sum of all primes up to 2 million

I made a program that returns the sum of all primes less than 2 million. I really don’t know what is happening with this, I get 142891895587 as my answer when the correct answer is 142913828922. It seems that it lacks some prime numbers. I am sure that the getPrime function works as intended. I used it a couple of times earlier and worked correctly than. The code is as follows:

vector<int> getPrimes(int number);

int main()
{

    unsigned long int sum = 0;
    vector<int> primes = getPrimes(2000000);

    for(int i = 0; i < primes.size(); i++)
    {
        sum += primes[i];
    }

    cout << sum;

    return 0;
}


vector<int> getPrimes(int number)
{

    vector<bool> sieve(number+1,false);
    vector<int> primes;
    sieve[0] = true;
    sieve[1] = true;

    for(int i = 2; i <= number; i++)
    {
        if(sieve[i]==false)
        {
            primes.push_back(i);
            unsigned long int temp = i*i;
            while(temp <= number)
            {
                sieve[temp] = true;
                temp = temp + i;
            }
        }
    }
    return primes;
}
+3
source share
5 answers

The expression i*ioverflows because it iis int. It is truncated before the appointment temp. To avoid overflow, make him static_cast<unsigned long>( i ) * i.

, : for(int i = 2; i*i <= number; i++).

.

, (un) , , : int , §4.7/2, .

+10

:

unsigned long int temp = i*i;
+1

. , temp. sieve? i, ? , , ?

, , . - . 2 , , , 30. , . , .

. - , .

. , getPrimes , . ( , - .)

0

64- . :

unsigned long int temp = i * i;

, int, int (32-). :

unsigned long int temp = (unsigned long int) i * i;

My system has a long 32-bit, so I had to change both temp, and sumto unsigned long long.

0
source

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


All Articles