In: Computer Science
Write a C++ program to check whether a number is prime or not. A prime number is a positive integer that has exactly two positive integer factors, 1 and itself. Eg: 2, 3, 5, 7, 11, 13, 17, ...
Sample Output:
Input a number to check prime or not: 13 The entered number is a
prime number.
Input a number to check prime or not: 28 The entered number is not a prime number.
Enhance the program to list all factors if the number is not
prime Input a number to check prime or not: 28
The entered number is not a prime number.
Factors: 1, 2, 4, 7, 14, and 28
#include <iostream>
#include <array>
using namespace std;
int main()
{
int n, m = 1;
cout<<"Input a number to check prime or not: ";
cin>>n;
int *count = new int; // dynamic intialization of an array
count[0] = 1; //the number 1 is alwas divides every numbers and
this is 1st index in the array
bool flag;
for(int i=2; i <= n/2; i++) //the index "i" count from 2 to falf
of the given number
{
if(n%i == 0) // if the number n is divisible by i then it is not a
prime number
{
count[m++] = i; //stores the all the factors of the given number
n
flag = true; //set to true if the number is not a prime
}
}
if(flag == false)
cout<<"The entered number is a prime number";
else
{
cout<<"The entered number is not a prime number \n";
cout<<"Factors: ";
for(int i=0;i<m;i++)
cout<<count[i]<<", ";
cout<<"and "<<n;
}
return 0;
}