I need to create a program that takes ‘N’ as Input and show the first N prime numbers and finally sum them…
Here’s my code, but it doesn’t work. (It loops at: “if ((num == 2) || (num == 3))”)
Can you help me?
Thanks in advance.
I can’t use functions and arrays.
Code:
#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;
}
To begin with, you are using a variable name
restoinstead ofrest, which is the name with which you declared it (if (resto == 0)).Second, you increase
numtwice: at the beginning and at the end of your loop. Remove the lastnum++and it should work better.Third, initialize
contto 1 and not to 0, or it will compute sum of the first N+1 primes instead of the first N primes.Here is the fixed version of your code: