Having issues creating a program to determine whether or not the number that the
ID: 3851001 • Letter: H
Question
Having issues creating a program to determine whether or not the number that the user inputs is prime or not prime. By the prime definition, a natural number p is prime if and only if p is greater than 1 and the only natural numbers that divide p are 1 and p. Now I know, for it to be prime as well it can only be divisble by 2 natural numbers. How would I set the condition to where the divisibilty of the number that the user inputs is equal to 2 that way if its more than 2 it'll display that the number that the user entered is not prime.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int p;
cout << endl << "Enter a positive integer: ";
cin >> p;
if (p > 1 && (p/p || p/1))
{
cout << "prime" << endl;
}
else
{
cout << "not prime" << endl;
}
return 0;
}
Explanation / Answer
You cannot solve the problem in this way(the code what you have written above).To check whether a number is prime or not you just count the number of factors of that number.If it has exactly two factors(one and itself) then it is a prime number.Here is the code:
#include<iostream>
using namespace std;
int main()
{
int p,i,count;
cout<<" Enter a positive number:";
cin>>p;
count=0; //Intially no.of factors are zero
if(p>0) //to check positive number
{
for(i=1;i<=p;i++) //To check factors from one to p(itself)
{
if(p%i==0) //if it is true then i is a factor of p
{
count++; //Then increase the count by 1
}
}
if(count==2) //Exactly two factors 1 and itself
{
cout<<"Prime"<<endl;
}
else
{
cout<<"Not prime"<<endl;
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.