Answer to Question #181420 in C++ for Darren

Question #181420

A positive integer n is said to be prime (or, "a prime") if and only if n is greater than 1 and is divisible only by 1 and n. For example, the integers 17 and 29 are prime, but 1 and 38 are not prime. Write a function named "is_prime" that takes a positive integer argument and returns as its value the integer 1 if the argument is prime and returns the integer 0 otherwise. Thus, for example:


cout << is_prime(19) << endl;    // will print 1

cout << is_prime(1) << endl;     // will print 0

cout << is_prime(51) << endl;   // will print 0

cout << is_prime(-13) << endl; // will print 0

1
Expert's answer
2021-04-17T11:13:12-0400
#include <iostream>

using namespace std;

bool is_prime(int n){
  int i, m=0, flag=0;
  m=n/2;
  bool answer;
  if(n<=1){
      answer=0;
  }
  else{
  for(i = 2; i <= m; i++)  
  {  
      if(n % i == 0)  
      {  
          answer=0;
          flag=1;
          break;  
      }  
  }  
  if (flag==0)  
      answer=1;
  }      
  return answer;
    
}

int main()
{
    cout << is_prime(19) << endl; // will print 1
    cout << is_prime(1) << endl;     // will print 0
    cout << is_prime(51) << endl;   // will print 0
    cout << is_prime(-13) << endl; // will print 0

    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
APPROVED BY CLIENTS