Find Prime Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
	int n;
	cout << "Enter the value of n: ";
	cin >> n;

	bool* prime = new bool [n+1];
	for (int i = 1; i <= n; i++)
	{
		prime[i] = true;
		for (int j = 2; j < i; j++)
		{
			if (i % j == 0)
				prime[i] = false;
				break;
			}
	}
	system("pause");
	delete [] prime;
	return 0;
}


My code has any wrong??
how to check the prime number be false??
and,
how to make a output like this
Enter the value of n: 10 
Prime numbers: 2, 3, 5, 7 
4 primes found.


I have no idea....
please help
Last edited on
Something as (without testing):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::cout << "Prime numbers: ";
bool successive = false;
int count = 0;
for ( int  i = 1; i <= n; i++ )
{
   if ( prime[i] )
   {
      std::cout << ( successive ? ", " : "" ) << i;
      successive = true;
      ++count;
   }
}

std::cout << '\n' << count << " primes found" << std::endl;
I don't understand std:: .....
I am still a beginner
Last edited on
If you included directive

using namespace std;

in your program then you can remove std::

For example

cout << "Prime numbers: ";
Last edited on
Thanks vlad I got your point

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

int main()
{
	int n;
	cout << "Enter the value of n: ";
	cin >> n;

	bool* prime = new bool [n+1];
	for (int i = 1; i <= n; i++)
	{
		prime[i] = true;
		for (int j = 2; j <= i; j++)
		{
			if (i % j == 0)
				prime[i] = false;
				break;
			}
	}
	
	cout << "Prime numbers: ";
	bool range = false;
	int count = 0;
	for ( int k = 1; k <= n; k++)
	{
		if (prime[k])
		{
			cout << (range ? "," : "") << k;
			range = true;
			++count;
		}
	}
	cout << endl << count << " " << "primes found. " << endl;
	
	system("pause");
	delete [] prime;
	return 0;
}


This is my update program
My output like this
Enter the value of n: 10 
Prime numbers: 1, 3, 5, 7, 9 
5 primes found.


I cannot make a right prime number
What is wrong in my checking???
Last edited on
It is obvious that this loop

1
2
3
4
5
6
		for (int j = 2; j <= i; j++)
		{
			if (i % j == 0)
				prime[i] = false;
				break;
			}


is incorrect. As when j == i then i % j will be always equual to 0 even for prime numbers. Secondly, these two statements

1
2
				prime[i] = false;
				break;


shall be enclosed in braces.
Thank vlad,
I finish it
Thank you so much~~
Topic archived. No new replies allowed.