小于2,000,000的素数总和给出错误的结果 [英] Sum of prime numbers below 2,000,000 giving wrong result

查看:56
本文介绍了小于2,000,000的素数总和给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将所有小于2,000,000的素数相加,但是我的代码给出的结果是错误的(1,179,908,154正确的是142,913,828,922),因为它可以与较低的值完美配合,所以我无法弄清楚出了什么问题.

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;
}

推荐答案

您正在将 ans 声明为 unsigned int ,在当今的大多数计算机上,这是32位的,即可以代表从 0 4294967295 的数字,但是200万以下的所有质数之和绝对超过 4294967295 ,请尝试使用而不是unsigned long long .

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:

这篇关于小于2,000,000的素数总和给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆