Write the function bool isPrime(int n) that returns true if n is a prime number,
ID: 3556155 • Letter: W
Question
Write the function bool isPrime(int n) that returns true if n is a prime number, and false
otherwise. Write a program that will exercise this function.
Example run (with user input indicated with bold italics):
Enter an integer or Q to quit: 10
10 is not prime.
Enter an integer or Q to quit: 31
31 is prime.
Enter an integer or Q to quit: Q
Enter an integer or Q to quit: 10
10 is not prime.
Enter an integer or Q to quit: 31
31 is prime.
Enter an integer or Q to quit: 9999
9999 is not prime.
Enter an integer or Q to quit: 7919
7919 is prime.
Enter an integer or Q to quit: Q
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n){
for(int i=2;i<=sqrt(n);i++){ // checking if n has any divisor
if(n%i==0) return false;
}
return true;
}
int main() {
int n;
cout<<"Enter an integer or Q to quit: ";
while(cin>>n) {
if(!isPrime(n) )
cout<<n<<" is not prime."<<endl;
else
cout<<n<<" is prime."<<endl;
cout<<"Enter an integer or Q to quit: ";
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.