In: Computer Science
C++
Create a program that checks whether a number is a prime number and displays its factors if it is not a prime number.
Console
Prime Number Checker
Please enter an integer between 1 and 5000: 5
5 is a prime number.
Try again? (y/n): y
Please enter an integer between 1 and 5000: 6
6 is NOT a prime number.
It has 4 factors: 1 2 3 6
Try again? (y/n): y
Please enter an integer between 1 and 5000: 200
200 is NOT a prime number.
It has 12 factors: 1 2 4 5 8 10 20 25 40 50 100 200
Try again? (y/n): n
Bye!
Specifications
#include <iostream>
using namespace std;
int isPrime(int n)
{
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main(){
int n;
char ch = 'y';
while(ch=='y'){
cout<<"Please enter an integer between 1 and 5000: ";
cin>>n;
if(isPrime(n)){
cout<<n<<" is a prime number."<<endl;
}
else{
int count = 0;
for(int i = 1;i<=n;i++){
if(n%i==0){
count++;
}
}
cout<<"It has "<<count<<" factors: ";
for(int i = 1;i<=n;i++){
if(n%i==0){
cout<<i<<" ";
}
}
cout<<endl;
cout<<n<<" is NOT a prime number."<<endl;
}
cout<<"Try again? (y/n): ";
cin>>ch;
//cin>>ch;
}
cout<<"Bye!";
return 0;
}