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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With