Answer to Question #316136 in C++ for Maaz Ahmed

Question #316136

Write a c++ program code that enters a number and prints wether or not it is prime number?

1
Expert's answer
2022-03-22T15:20:40-0400
#include <iostream>
using namespace std;


bool is_prime(unsigned x) {
    if (x <= 1)
        return false;
    if (x == 2)
        return true;
    if (x % 2 == 0)
        return false;
    
    unsigned n = 3;
    while (n*n <= x) {
        if (x % n == 0)
            return false;
        n += 2;
    }
    return true;
}


int main() {
    unsigned x;


    cout << "Enter a positive integer: ";
    cin >> x;


    if (is_prime(x))
        cout << "It is a prime number" << endl;
    else
        cout << "It 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