C++ A prime number is an integer greater than 1 that is evenly divisible by only
ID: 3864897 • Letter: C
Question
C++
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.
HINT: Review the functionality of the % (modulus) operator
Explanation / Answer
// C++ code
#include <iostream>
using namespace std;
bool isPrime(int n)
{
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(isPrime(n) == true)
cout << n << " is Prime ";
else
cout << n << " is not Prime ";
}
/*
output:
Enter a number: 5
5 is Prime
Enter a number: 6
6 is not Prime
Enter a number: 11
11 is Prime
Enter a number: 15
15 is not Prime
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.