### check for prime numbers using only IF-ELSE

hello guys i'm trying to make a program to check for a user input if it prime or not, by only using if-else statements , can you help me ?

 ``123456789101112131415161718192021222324252627282930`` ``````#include using namespace std; int main () { int n; cout << "Enter an intger !"<>n; if(n == 2) cout<<"2 is the only even prime number"<
Last edited on
Unless the user input is limited to a very small range of values, using only if-else is not really feasible. The amount of coding required could be huge (unless you used some sort of macro to construct the code).

#include <iostream>

using namespace std;
int main ()
{

int n;
cout << "Enter an integer !"<<endl;
cin>>n;

if (n%2==0)
cout << n<< " is not prime number" << endl;

else if (n%2==1)
cout<<n<<" is a prime number"<< endl;

system("pause");
return 0;

}
I think by using this will pretty much tell the user the number is prime or not
i already tried it , it giving me that '9' is prime number
closed account (Dy7SLyTq)
its not going to work. you need a while loop and xsxs's will only test for evens and odds
You can do it using recursion :)

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include using std::cout; using std::endl; using std::cin; bool IsPrime(unsigned& test_number, unsigned check_number) { ++check_number; if (test_number == check_number) return true; if (test_number % check_number == 0) { cout << test_number << " can be divided by " << check_number << endl; return false; } return IsPrime(test_number, check_number); } int main() { cout << "Enter a number > 0: "; unsigned test_number = 0; cin >> test_number; if (IsPrime(test_number, 1)) cout << test_number << " is a prime number" << endl; else cout << test_number << " is not a prime number" << endl; return 0; }``````
closed account (Dy7SLyTq)
didnt think of that
Well, if it can be done using if-else + a recursive function, it could also be done using if-else + goto or if-else + while or if-else + something.
I actually think you can do it using template recursion too, the number of values you'd accept would be limited by how much recursion you did and compile time would increase as well, but it should be possible.

Topic archived. No new replies allowed.