The result you’re after might be too large to represent through a 32-bit signed integer (int
).
Let’s first determine the result’s upper bound by assuming that all numbers are prime. Through summation, we know that the sum of all numbers up to N
(inclusive) is N * (N + 1) / 2
; thus, the upper bound for the sum of all primes up to 2,000,000 is 2,000,001,000,000. This is larger than the maximum value allowed by int
, 2,147,483,647, so you’re probably getting a numeric overflow which is silently ignored.
If you wanted a more accurate estimate of your answer, you could use the prime number theorem, which states that the probability of a random integer between 0 and N
being prime is approximately 1 / ln(N)
. Combining this with our previous formula, the approximate sum of all primes up to N
is N * (N + 1) / (2 * ln(N))
. For 2,000,000, this evaluates to around 138,000,000,000, which is still larger than the maximum value for int
.
To resolve your problem, you could simply switch the integral data type you’re using for the soap
variable to a 64-bit integer representation, such as long
. Its maximum value is 9,223,372,036,854,775,807, so it would definitely be able to represent your number.
long soap = 0;
On a separate note: Since you’re working with sequences of primes, you could achieve a huge performance gain (at least 100×) if you change your implementation to a Sieve of Eratosthenes.