c++ - 2000000 以下的质数之和?

标签 c++ sum primes

我如何找到小于 200 万的所有素数的总和?欧拉计划第十题,http://projecteuler.net/problem=10 . 我测试了我的代码低于 10 并且工作得很好。但是低于 200 万似乎不起作用:/已经大约 15 分钟了,而且还在继续,我认为不应该花那么长时间,对吗?我将尝试 sum 函数,但我仍然不明白为什么它不起作用?

编辑:我想我不能使用 sum 函数,因为数字甚至没有存储在数组中:/

我的代码:

#include <iostream>

using namespace std;

int main()
{
    unsigned long long x,y,z=0,s[200000],a,sum=0;
    bool isprime;
    for(x=3;x<2000000;x++)
    {
        for(y=2;y<x;y++)
        {
            if(x%y!=0 && x!=y)
            {
                isprime =true;
            }
            else
            {
                isprime =false;
                break;
            }
        }
        if(isprime ==true)
        {
                s[z] = x;
                z++;
                isprime = false;
        }
    }
    cout<<z;
    for(a=0;a<z;a++)
    {
        sum=sum+s[a];
        cout<<"Sum is being calculated "<<sum<<"\n";
    }
    cout<<"The sum is "<<sum+2<<" LADIES";
}

最佳答案

你的问题是你的程序会检查太多不必要的除数。

为了检查给定整数是否为素数,您需要检查它是否没有小于或等于其平方根的除数。因为,如果有一个大于平方根的除数,商就是一个整数,并且小于平方根。

#include <iostream>

using namespace std;

int main()
{
    unsigned long long x,y,z=0,s[200000],a,sum=0;
    bool isprime;
    for(x=3;x<2000000;x++)
    {
        for(y=2; y*y <= x ;y++)
        {
            if(x%y!=0 && x!=y)
            {
                isprime =true;
            }
            else
            {
                isprime =false;
                break;
            }
        }
        if(isprime ==true)
        {
                s[z] = x;
                z++;
                isprime = false;
        }
    }
    cout<<z;
    for(a=0;a<z;a++)
    {
        sum=sum+s[a];
        cout<<"Sum is being calculated "<<sum<<"\n";
    }
    cout<<"The sum is "<<sum+2<<" LADIES";

您可以改用 vector :

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    unsigned long long x,y;
    std::vector<unsigned long long> primes;
    bool isprime = true;

    for(x=3; x<2000000; x++)
    {
        isprime = true;
        for(y=2; y*y <= x ;y++)
        {
            if(x%y==0 || x==y)
            {
                isprime=false;
                break;
            }
        }
        if(isprime)
        {
            primes.push_back(x);
        }
    }
    unsigned long long sum = 2 + std::accumulate(v.begin(), v.end());
    cout<<"The sum is "<<sum<<" LADIES";
}

关于c++ - 2000000 以下的质数之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16106171/

相关文章:

r - 基于行和列总和的 0 和 1 条件随机矩阵

sum - 任何有效的方法来计算第 n 项的谐波级数的总和? 1 + 1/2 + 1/3 + --- + 1/n =?

c++ - 有什么方法可以识别可用的内存地址吗?

带有线程的 C++ 主程序需要两次 Ctrl+C 才能退出

python - 是否可以对迭代器求和?

java - 使用埃拉托色尼筛法生成 k 个素数

f# - 生成无限的数字集

c++ - 为什么 stdin 和 stdout 看起来可以互换?

c++ - 在 Makefile 中链接 SDL 库,c++

algorithm - 多次生成质数