总结前N个素数

时间:2013-01-05 20:41:01

标签: c++ sum

我需要创建一个程序,将'N'作为输入并显示前N个素数,最后将它们相加... 这是我的代码,但它不起作用。 (它循环:“if((num == 2)||(num == 3))”)

你能帮帮我吗? 提前谢谢。

我无法使用函数和数组。

代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int n, num = 1, rest, cont = 0, sum = 0;
    bool exit = false;
    int e = 1;

    cout<<"How many prime number do you want to show? ";
    cin>>n;

    while (cont <= n)
    {
        num++;
        if ((num == 2) || (num == 3))
        {
            cout<<num<<endl;
            sum += num;
            cont++;
        }
        else if (num%2 == 0)
        {
        }
        else
        {
            bool exit = false;
            int div = 3;
            while (!exit)
            {
                rest = num%div;

                if (num == div)
                {
                    exit = true;
                    cout<<num<<endl;
                    sum += num;
                    cont++;
                }

                if (rest == 0)
                    exit = true;                    
                div++;
            }
        }       
        num++;
    }    
    cout<<"Sum: "<<sum<<endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

首先,您使用的是变量名resto而不是rest,这是您声明它的名称(if (resto == 0))。

其次,增加num两次:在循环的开头和结尾。删除最后一个num++,它应该更好。

第三,将cont初始化为1而不是0,否则它将计算前N + 1个素数的总和而不是前N个素数。

以下是您的代码的固定版本:

#include <iostream>

using namespace std;

int main()
{
    int n, num = 1, rest, cont = 1, sum = 0;
    bool exit = false;
    int e = 1;

    cout<<"How many prime number do you want to show? ";
    cin>>n;

    while (cont <= n)
    {
        num++;
        if ((num == 2) || (num == 3))
        {
            cout<<num<<endl;
            sum += num;
            cont++;
        }
        else if (num%2 == 0)
        {
        }
        else
        {
            bool exit = false;
            int div = 3;
            while (!exit)
            {
                rest = num%div;

                if (num == div)
                {
                    exit = true;
                    cout<<num<<endl;
                    sum += num;
                    cont++;
                }

                if (rest == 0)
                    exit = true;

                div++;
            }
        }
    }
    cout<<"Sum: "<<sum<<endl;

    return 0;
}