Coutning Primes

Hi, I am new to c++ and while I have seemed to have tackled the Prime Number program, I want to expand it to not only display the primes, but display the number of primes. I am completely confused as to how to go about it.

To wit...

Enter a number: x
There are y number of primes in x, they are:

a,b,c,d

Do you wish to continue (y/n)?

That is what I have so far (well, minus the "there are y number of primes" part. I have attempted do/while and if/else, but to no avail.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;

int main()
{
	int x; // input
	int y; // divisor
	int z; // prime
	
	char key; // to continue or not

	cout << "This program will allow you to enter a number and will display all and how many prime numbers from that number to 0." << endl << endl;


do
{
	cout << "Please enter a number: ";
	cin >> x;

	cout << endl;
	// cout << "There are " << counter << " primes in that range." << endl;
	cout << "All primes in this range are:" << endl << endl;

	for (z=x; z>=2; z--)
	{
		bool primeNo = false;

	for (y=2; y<z; y++)
	{
	
		if (z % y == 0)
		{
			primeNo = true;
		}
	}
		if (primeNo == false)
		{
			
			cout << z << " ";
			
		}
	}

	cout << endl << endl;
	cout << "Continue (y/n)? ";
	cin >> key;
}

	while (key == 'y'||key == 'Y');
	cout << endl << endl;
	
	system("PAUSE");

	return 0;

}



Thank you!
Well that is very rude. I apologise that that program is not an end all be all of all creation, but I have to start someone as at one point so did you and everyone else.

Perchance you have a solution that you opted not state, or you do not have one and simply wish to make a comment on others abilities, either way, in your case silence would have been golden.
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
int main()
{
	int x; // input
	int y; // divisor
	int z; // prime
	int counter;

	char key; // to continue or not

	cout << "This program will allow you to enter a number and will display all and how many prime numbers from that number to 0." << endl << endl;


do
{
    counter=0;

	cout << "Please enter a number: ";
	cin >> x;

	cout << endl;
	//
	cout << "All primes in this range are:" << endl << endl;

	for (z=x; z>=2; z--)
	{
		bool primeNo = false;

	for (y=2; y<z; y++)
	{

		if (z % y == 0)
		{
			primeNo = true;
		}
	}
		if (primeNo == false)
		{

			cout << z << " ";
			counter++; // <-------- increase the counter

		}
	}
    cout << "\nThere are " << counter << " primes in that range." << endl; // print the number of primes
	cout << endl << endl;
	cout << "Continue (y/n)? ";
	cin >> key;
}

	while (key == 'y'||key == 'Y');
	cout << endl << endl;

	system("PAUSE");

	return 0;

}

Last edited on
Topic archived. No new replies allowed.