...

# The Tired Prime Number Program, but different.

bohling
01-01-2012, 11:10 AM
Hi,

I have figured out the old tired prime number program that a lot of newbies like myself attempt to tackle when we hit the ground running with c++. What I am interested in is expanding it to something that not only displays the primes of a number, but the number of primes. To wit:

There are 4 primes in 10. Those primes are:

7 5 3 2

Do you wish to continue (y/n)?

I have all of that down except for the "there are x primes". I have tried count and if/else/do but I am getting hopelessly confused. Is there a simple or other way to do it?

Here is my code so far...

#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;

}

Spookster
01-01-2012, 12:27 PM
That is easy to do. Just create a variable to keep track of the number of primes. Each time you determine a prime, increment the number.

arih7nt
01-03-2012, 07:39 AM
Well I'm not so used to C++ but only C. I can't help with the syntax but maybe a little bit with the logic.

1. Try using an array to store all the primes ?
Well as a number is found to be a prime it is stored in an array and later when all the primes have been found the loop terminates and you print the array. And for the count maybe a variable who's count increases as you find each prime ?

2.Printing each Prime as it is found and having a variable increment along, finally as the loop ends. Printing the Increment to give the total number of primes.

I haven't tried either of the concepts on C, I'll give it a try and incase it works, I'll bring it up here.

Let me know if any of it works for you.