Printing prime numbers

Sep 11, 2015 at 6:33pm
What does count and num does?Why is num inititalized to 3?why is square root of 3 in for loop?

#include<iostream>
#include<cmath>

using namespace std;

int main()
{
int n, status = 1, num = 3, count, c;

cout << "Enter the number of prime numbers to print\n";
cin >> n;

if (n >= 1)
{
cout << "First " << n << " prime numbers are :-" << endl;
cout << 2 << endl;
}

for (count = 2; count <= n; )
{
for (c = 2; c <= (int)sqrt(num); c++)
{
if (num%c == 0)
{
status = 0;
break;
}
}
if (status != 0)
{
cout << num << endl;
count++;
}
status = 1;
num++;
}

system("pause");
}
Sep 11, 2015 at 6:40pm
What does count and num do?

count is the number of primes found.
num is the number that is being tested to determine if it is prime.
Why is num initialized to 3

That is the first prime > 2.
why is square root of 3 in for loop?

A factor of a prime number can't be greater than its square root, so no point in checking values greater than the square root.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.





Sep 11, 2015 at 6:50pm
Thanks for your reply
Topic archived. No new replies allowed.