素数总和低于200万 [英] sum of primes under 2000000

查看:144
本文介绍了素数总和低于200万的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这个程序找到所有的低于200万的素数的总和,但由于某种原因,我得到一个远低于我应该期望的数字。

I'm trying this program to find the sum of all the primes under two million, but for some reason I am coming up with a number far below what I should be expecting.

这是我的代码。一个共同工作说,我可能不会捕获所有的素数与我的程序,但他不知道C + +,我不知道我怎么可能失去他们。

Here is my code. A co-working says I might not be catching all the primes with my program but he doesn't know C++ and I don't see how I could be missing them.

#include <iostream>

using namespace std;

int main()
{
    int a = 500000;
    int e = 0;

    // this is an array to hold all the prime number i find,
    // it's initialized to the arbitrarily high number of 500000
    int list[a]; 

    //here i am initializing the first members of my list to the first primes
    list[0] = 2; 
    list[1] = 3;
    list[2] = 5;
    a = 3; // i set a = 3 to catch the next coming prime of 7
    for (int c = 5; c < 2000000; c++)
    {
        // this bool is for prime catching, 
        // if d is false then the number will not be saved into the array
        bool d = false; 

        // this bool is for an exit statement in the following iterative loop, 
        // if it's false the loop will exit
        bool h = true; 
        for (int i = 0; list[i] < c/2 + 1 && h == true; i++)
        {
            // this checks to see if a number is evenly 
            // divisable by any of my primes so far
            if (c % list[i] == 0) 
            {
                d = false;
                h = false;
            }
        }
        if (d == true)
        {
            list[a] = c; // if i find a prime i save it into my array
            e += c; // if i find a prime i sum it to my total
            a++;
        }
    }
    cout << e; 
}


推荐答案

d 总是永远是假的。没有代码将它设置为 true

d is always and forever false. No code ever sets it to true.

此外,您需要启动 / code> at 10(2 + 3 + 5)。

Also, you need to start e at 10 (2 + 3 + 5).

这篇关于素数总和低于200万的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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