#include <iostream>
#include <cmath> //To use sqrt
usingnamespace std;
bool IsPrime(int num)
{
if(num<=1)
returnfalse;
if(num==2)
returntrue;
if(num%2==0)
returnfalse;
int sRoot = sqrt(num*1.0);
for(int i=3; i<=sRoot; i+=2)
{
if(num%i==0)
returnfalse;
}
returntrue;
}
int main()
{
cout << "Please enter a number to ckeck it : " ;
int Number ;
cin >> Number;
if (IsPrime(Number))
cout << "Wow this is a prime number ... " << endl;
else
cout << "O.o This is not a prime number :(" << endl;
cin.get();
return 0;
}
#include <iostream>
#include <cmath> //To use sqrt
usingnamespace std;
bool IsPrime(int num)
{
if(num<=1) // if number is less than one
returnfalse; //return 0 to the caller
if(num==2)// if number is equal to two
returntrue;//return 1 to the caller
if(num%2==0) // if the remainder of the number divided by two is zero
returnfalse;// return 0 to the caller
int sRoot = sqrt(num*1.0);// Declare variable that is equal to the squareroot of the number times by one.
for(int i=3; i<=sRoot; i+=2)//for i = 3 and i is less than or equal to the squareroot of the number, add two each time
{
if(num%i==0)// if the number divided by i has no remainder
returnfalse;//then return 0 to caller
}
returntrue;// or else it will return 1
}
int main()
{
cout << "Please enter a number to ckeck it : " ;// outputs question to console
int Number ;// declares integer variable
cin >> Number;// waits for user to input variable
if (IsPrime(Number))//calls the function with users number as parameter inside if statement
cout << "Wow this is a prime number ... " << endl;// if returns 1 output statement to console
else
cout << "O.o This is not a prime number :(" << endl;//if returns 0 output statement to console
cin.get();//used to pause
return 0;
}
also if you were wondering what the function actually does which im presuming you were.
It takes the number and finds the square root of it.
The number is then divided by any number under the square.
If the modulus(%) of the number is 0 then it is divisible.
If none of these numbers are divisible then it must be a prime number.