18.
>Prime Numbers with a Twist
Ques. Write a code to check whether no is prime or not. Condition use function
check() to find whether entered no is positive or negative ,if negative then enter
the no, And if yes pas no as a parameter to prime() and check whether no is prime
or not?
Whether the number is positive or not, if it is negative then print the message
“please enter the positive number”
It is positive then call the function prime and check whether the take positive
number is prime or not.
Ans =
#include <iostream>
using namespace std;
bool check(int n) {
if (n < 0) {
cout << "Please enter a positive number.\n";
return false;
}
return true;
}
bool prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (!check(n)) {
return 0;
}
if (prime(n)) {
cout << n << " is a prime number.\n";
} else {
cout << n << " is not a prime number.\n";
}
return 0;
}