Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with adding prime numbers in C++ [closed]

Tags:

c++

My code works for numbers up to 300 or 20. But it doesn't work for 2000000. I tried using long instead, but it still didn't work.

#include <iostream>
bool prime(int i) {
    bool result = true;
    int isitprime = i;

    for (int j = 2; j < isitprime; j++) { ///prime number tester
        if (isitprime % j == 0) {
            result = false;
            break;
        }
    }

    return result;
}

int main(void) {
    using namespace std;
    long sum = 0;

    for (long i = 2; i <= 2000000; i++) {
        if (prime(i)) {
            sum += i;
        }
    }

    cout << sum << endl;
    system("pause");
    return 0;
}
like image 389
Boom_mooB Avatar asked Feb 19 '26 03:02

Boom_mooB


1 Answers

I believe that the sum of primes less than 2000000 is 142913828922 but the maximum value of a long integer is 2147483647 which is not large enough to store this sum.

like image 84
mathematician1975 Avatar answered Feb 21 '26 17:02

mathematician1975