Question 1, relates to question 2....Using C++ Question 2 Write a program that d
ID: 3699977 • Letter: Q
Question
Question 1, relates to question 2....Using C++
Question 2
Write a program that determines if a number is prime. A Prime Number can only be evenly divided by 1 and itself. Thus, given a number n, if there are any factors of n between 1 and n, n is not a prime number. a) Main should handle al1 input and output b) Create an isPrime function: returns true if a number is prime - returns false if a number is not prime Example Output 1 Enter a number 15 Is . 2 a factor of 152 No Is 3 a factor of 15? Yes 15 is not a prime number Enter a number: 7 Is 2 a factor of 7? No. Is 3 a factor of 7? No. Is 4 a factor of 7? No. Is 5 a factor of 7? No. Is 6 a factor of 72 No 7 is a prime number.Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int num) {
for (int f = 2; f <= num / 2; f++) {
if (num % f == 0) {
return false;
}
}
return true;
}
int main() {
int n;
cout<<"Enter a number: "<<endl;
cin >> n;
for(int i=2;i<n;i++) {
if(n%i==0)
cout<<"Is "<<i<<" a factor of "<<n<<": Yes"<<endl;
else
cout<<"Is "<<i<<" a factor of "<<n<<": No"<<endl;
}
if(isPrime(n)) {
cout<<n<<" is a prime number."<<endl;
} else {
cout<<n<<" is a not prime number."<<endl;
}
return 0;
}
Output:
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.