I have to sum all prime numbers below 2,000,000 but my code is giving the wrong result(1,179,908,154 right is 142,913,828,922), since it\'s working perfectly with lower valu
You are declaring ans
as unsigned int
, on most machines today, that's 32-bit, which can represent numbers from 0
to 4294967295
, but the sum of all prime numbers under two million is definitely way over 4294967295
, try use unsigned long long
instead.
By the way, the algorithm you used is very inefficient, you may consider The sieve of Eratosthenes: