Error in listing out a series of prime numbers

i was given a assignment to release the first n prime numbers
it turned out to be alright for the first 8 prime number by showing 8 prime numbers. but when i tried 9, it gave me 7 prime numbers instead with a missing of 3 as a prime number. i can't figure out what's wrong with my programming. can anyone there help me please! thanks a lot


#include<iostream.h>
#include<math.h>
#include<stdlib.h>

int main(void)
{
int n , div, number, count;
bool prime;

cout<<"To tabulate the first n prime number."<<endl;
cout<<"Please enter n = ";
cin>>n;

cout<<endl;

cout<<"The prime numbers are "<<endl;
cout<<"2"<<endl;

count = 1;
number = 1;

do
{
number = number + 2;

prime = true;
div = 2;

do
{
if (number % div == 0)
prime = false;

else
div++;
}
while
(div <=sqrt(n) && prime ==true);

if(prime == true)
cout<<number<<endl;

count++;
}
while (count < n);

cout<<endl;

system("pause");
return 0;

}
div <= sqrt( number )

not

div <= sqrt( n )
thanks. the number 3 appears

but the numbers of prime number still does not equal to "n" input.

when i enter 10, it gave me 8 prime numbers
while (count < n);

should be

while (count <= n); //because count is initialized to 1 (not 0) ;)

Another point
- div should be initialized to 3, coz you're incrementing number by 2, so you're sure that even numbers are not going to be in the picture at all. No point "moduling" by 2.
Last edited on
it's still the same result.
the result is worse.

i entered 5, they gave me 4 with a missing number 3
Last edited on
1)
Why are you doing div <= sqrt( n )?

Should be:

div <= number/2

2)
1
2
3
4
if(prime == true)
cout<<number<<endl;

count++;


Change the above code as below:

1
2
3
4
5
if(prime == true)
{
cout<<number<<endl;
count++;
}
Last edited on
1) it's a mathetic formulae. it's fixed.

2) that solved everything. thanks a lot
Topic archived. No new replies allowed.