In: Computer Science
A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided by 1, 2, 3, and 6.
Write a Boolean function named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, and false otherwise. Demonstrate the function in a complete program.
Your program must have at least 3 user-defined functions is as follows:
get_input function
isPrime function
main function
Here's an algorithm to solve this problem:
// main function
do
{
// call get_input function to input a positive integer (whole numbers > 0)
// call isPrime function.
// send the positive integer returned from get_input as an argument to isPrime.
// if the value returned from isPrime is true,
// display that the input data (display the actual value of the number) is a prime number;
// else
// display that the input data (display the actual value of the number) is not a prime number;
// prompt user to input an answer whether he/she wants to go through the above process with
// another positive integer.
// get the user’s answer.
} while (answer == ‘y’ || answer == ‘Y’)
// get_input function
// prompt the user to input an integer.
// do data validation on the entered integer;
// that is, set up a loop, and as long as the integer is not
// positive, have the user enter a positive integer.
// once a positive integer is entered, that integer needs to be returned back to the main
// function.
// isPrime function
// this function receives a positive integer as a parameter.
// this function returns a value of true or false back to main.
in C++
ANSWER:-
#include
using namespace std;
int get_input()
{
int n;
do
{
cout<<"enter a number :
";
cin>>n;
}while(n<=0);
return n;
}
bool isPrime(int n)
{
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
int main() {
int n;
char answer;
bool res;
do
{
n=get_input();
res=isPrime(n);
if(res)
cout<<"the number
"<
cout<<"the number
"<
cin>>answer;
}while (answer == 'y' || answer == 'Y');
return 0;
}
OUTPUT:-
enter a number : 5 the number 5 is prime if you want above process again enter y/Y : y enter a number : 6 the number 6 is not prime if you want above process again enter y/Y : n