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 ?

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
#include <iostream>

using namespace std;
int main ()
{
    
int n;
cout << "Enter an intger !"<<endl;
cin>>n;

	

       if(n == 2)	
		cout<<"2 is the only even prime number"<<endl;

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

       if ((n%3==0) || (n%5==0) || (n%7==0))
                     cout<< n<<" is prime number"<<endl;
        
                  else  if  (n%2==1)
                     cout<<n<<" is mot a prime number"<< endl;
                              
      
        
system("pause");
return 0;

}
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 :)

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
#include <iostream>

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.