# Answer to Question #17690 in C++ for priya

Question #17690

Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.)

Expert's answer

#include <iostream>

#include <cmath>

int main()

{

signed input = 0;

std::cout << "Please enter a positive integer: ";

std::cin >> input;

std::cout << "Your have entered this integer: " << input << std::endl;

if (input <= 0)

return 1;

unsigned number = input;

bool even = (number % 2 == 0);

bool prime = false;

if (number == 1)

prime = true;

else if (even)

prime = (number == 2);

else

{

unsigned sqroot = static_cast<unsigned>(sqrt(number));

if (number == sqroot * sqroot)

prime = false;

else

{

bool divisible = false;

for (unsigned oddn = 3; oddn <= sqroot; oddn += 2)

{

if (number % oddn == 0)

{

divisible = true;

break;

}

}

prime = !divisible;

}

}

std::cout << number << " is " << (prime ? "a" : "not a") << " prime number"

<< std::endl;

}

#include <cmath>

int main()

{

signed input = 0;

std::cout << "Please enter a positive integer: ";

std::cin >> input;

std::cout << "Your have entered this integer: " << input << std::endl;

if (input <= 0)

return 1;

unsigned number = input;

bool even = (number % 2 == 0);

bool prime = false;

if (number == 1)

prime = true;

else if (even)

prime = (number == 2);

else

{

unsigned sqroot = static_cast<unsigned>(sqrt(number));

if (number == sqroot * sqroot)

prime = false;

else

{

bool divisible = false;

for (unsigned oddn = 3; oddn <= sqroot; oddn += 2)

{

if (number % oddn == 0)

{

divisible = true;

break;

}

}

prime = !divisible;

}

}

std::cout << number << " is " << (prime ? "a" : "not a") << " prime number"

<< std::endl;

}

## Comments

## Leave a comment