bohling
01-01-2012, 10: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:
Please enter a number: 10
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;
}
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:
Please enter a number: 10
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;
}