Answer to Question #303760 in C++ for core

Question #303760

 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.



1
Expert's answer
2022-02-28T13:55:08-0500
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);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog