我需要创建一个将“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;
}