[C++] Prime Number Program
Tells if number is prime or not.
Ask questions if you have them.
Ask questions if you have them.
#include <iostream.h>
#include <math.h>
int main()
{
int num, x=0;
cout<<"Enter a number: ";
cin>>num;
while(num<2)//deals with incorrect user input
{
cout<<"No, a number larger than 1."<<endl;
cout<<"Try again: ";
cin>>num;
}
for (int i=2; i<=sqrt(num)&&x==0; i++)// basically saying divide your number by 2, then 3, so on.
{ //sqrt because you only need to check first half of the numbers of the inputted number
if (num % i == 0)//if at any time, the number divides perfectly, it's not prime
{
x=num; //this breaks the loop
cout << "It is not prime number." << endl;
cout<<num<<"/"<<i<<"= "<<num/i<<endl;
}
}
if(x==0)//if the value we've set as x is still zero, nothing was divided perfectly, it's prime.
{
cout<<"Yes, that's a prime number."<<endl;
}
system ("PAUSE");
return 0;
}