Finding the sum of primes between intervals (C ++ program does not work for large numbers)

My code is below. It works fine until the gap is very large. However, whenever I switch to a million, the program stops. for example, for intervals from 2 to 2,000,000, the sum of primes should be 142913828922 (on the back of the book), while my application shows 1179908154. Maybe someone can indicate where I made a mistake.

#include <iostream> #include <math.h> #define BELOW 2000000; using namespace std; bool isPrime(int num) { int i; for (i = 2; i <= sqrt(num); i++) { if (num % i == 0) { return 0; } else { ; } } } int main() { long sum = 0; for (int i = 2; i < BELOW i++) { if (isPrime(i)) { sum = sum + i; printf("sum: %ld\n", sum); } } cin.get(); return 0; } 
+6
source share
2 answers

The problem you're dealing with is integer overflow .

(signed) long can on most machines have values โ€‹โ€‹between -2147483647 and 2147483647 .

You should use a larger data type, I would suggest unsigned long long , which on most machines can store values โ€‹โ€‹between: 0 to 18446744073709551615 (at least 64 bits) or uint64_t .

+4
source

You must replace all occurrences of "int" and "long" with "uint64_t"

+1
source

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


All Articles