A prime number is a number that is evenly divisible only by itself and 1. For example, the number 5 is prime because it can be evenly divided only by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6. Write a C++ program using a function that takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Demonstrate the function in a complete C++ program.
using namespace std;
int is_prime(int n)
{
int i, Flag = 1;
if (n == 0 || n == 1) Flag=0;
else
{
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0) Flag = 0;
}
}
return (Flag);
}
int main()
{
int n=0;
while(n<=0)
{
cout<<"\n\tEnter a number (>0): "; cin>>n;
}
if(is_prime(n)==1) cout<<"\n\tThe number "<<n<<" is a PRIME NUmber";
else cout<<"\n\tThe number "<<n<<" is NOT a PRIME NUmber";
return(0);
}
Comments
Leave a comment