ume$h wrote:
Why does this program fail to run?
Define "fail to run". Does it not compile? Does it give erroneous output?
See FAQ 5.8
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
//FIRST n PRIMES
#include <iostream.h>
Non-standard header. #include <iostreamisntead
#include <math.h>
using namespace std; // to get cin and cout.
>
int main(void)
void in this context is superfluous and discouraged in C++.
{
long int i,j=3,count=1;
int n,flag=0;
poor practice. Better practice is one declaration per line.
Define i inside the for loop. e.g. for (int i = 1; ...)
cout<<"How many primes?";
cin>>n;
cout<<"2, ";
while(count<n)
{
for(i=1;i<(sqrt(j)+1);++i){
Hint: if you only check odd numbers for primality (see below), you can
increment i by 2 instead of 1.
if(j%i==0) {flag=1;break;}
Your problem lies here. Hint. What is the initial value of i?
What is the value of j%i, for any j, given that initial value of i?
Also, formatting -- put the body of the if on a separate line.
if(j>3 && flag==0) {cout<<j<<", ";++count;}}
Ditto here.
++j;
Hint: 2 is the only even prime. You can bump j by 2.
}
return 0;
}