So I need to write a program which tells the user if the number they input is prime or not. I have done so and included the code below. My problem is that I need to allow the user to input if they want to enter another number after the first one using y or n and I am having trouble figure it out. Any help would be appreciated. Thanks!
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
int number;
do
{
cout <<"Please enter a positive integer:";
cin>> number;
if((number%2==0) ||(number%3==0) || (number%4==0)||(number%5==0)||(number%6==0)|| (number%7==0)||(number%8==0)||(number%9==0))
cout <<"The number "<<number<<" is not a prime number" << endl;
elseif((number/1==number) && (number/number==1))
cout << "The number "<<number<<" is a prime number" << endl;
}
while(number>0);
cout << "Please enter a positive integer" << endl;
system("PAUSE");
return (0);
}
This test is never reached, since if you test let's say number 81
(number%3==0)
will be tested first to true, leaving out the rest of the comparisons.
On the other hand, what about other numbers divisibles by other prime numbers like 121? (divisible by 11)
The main idea of a prime number is that it will divide only with 1 and itself. The key-word is ONLY, as ANY number will divide with 1 and itself. So there isn't any point in doing this:
1 2 3 4
elseif((number/1==number) && (number/number==1))
cout << "The number "<<number<<" is a prime number" << endl;
.
Regarding prime numbers, there also is a rule(axiom) that states that when checking a number if is prime or not, you should check if the number divides to any number at least equal ( <= ) to it's half (the number to be checked / 2 -->> because 2 it's the smallest number that will make your number non-prime).
//header
bool IsPrime(int Number)
{
for(int i = 2; i < Number / 2 + 1; i++)
if(Number % i == 0)
returnfalse;
// as I said, you don't need to check no. > than 1/2 of your no.
//however, if your no. is odd - like 11 - you will need to check 1 no.
//more after the half of you initial no.-> i < Number / 2 + 1returntrue;
}
int main()
{
int number;
cin>> number;
if (IsPrime(Number))
cout<< "Prime!";
else
cout<<"Not prime";
return 0;
}
This is the simplest and rapid way, not the best one.
An advantage here is that this is computed at compile time if 'number' is an integral constant, hence the constexpr.
If you already have an array smallPrimes[] of small prime numbers up to that square root, then you could use smallPrimes[i] instead of div, with int i as parameter. That would speed up the calculation.