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

微笑、不失礼 提交于 2019-12-02 00:05:17

问题


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 values I can't figure out what's wrong.

#include <iostream>
using namespace std;

int main(){ 
    unsigned int j, i=2,ans=2, interval=2000000;

    while(i<=interval){
        i++;
        j=2;

        while(i!=j){            
            if(i % j != 0)
                j++;
            else{
                i++; j=2;}
        }

        if (i>=interval)
            break;

        cout << i<< endl;
        ans+=i;
    }

    cout << ans;

    cin.get();
    return 0;
}

回答1:


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:



来源:https://stackoverflow.com/questions/22084060/sum-of-prime-numbers-below-2-000-000-giving-wrong-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!