Sum of prime numbers below 2,000,000 giving wrong result

后端 未结 1 1796
星月不相逢
星月不相逢 2021-01-20 11:21

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

相关标签:
1条回答
  • 2021-01-20 11:39

    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:

    0 讨论(0)
提交回复
热议问题