Answer to Question #329308 in C++ for Zaki

Question #329308

Write a program in C++ that ask the user to type a value and check whether it is prime or not.

1
Expert's answer
2022-04-16T06:48:29-0400
#include <iostream>
using namespace std;


bool is_prime(int x) {
    if (x <=1 ) {
        return false;
    }
    if (x == 2) {
        return true;
    }
    if (x % 2 == 0) {
        return false;
    }


    int i = 3;
    while (i*i <= x) {
        if (x % i == 0) {
            return false;
        }
        i += 2;
    }
    return true;
}


int main() {
    int n;


    cout << "Enter a positive number: ";
    cin >> n;
    if (is_prime(n)) {
        cout << n << " ia a prime number" << endl;
    }
    else {
        cout << n << " is not a prime number" << endl;
    }
    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