81 996
Assignments Done
98,5%
Successfully Done
In December 2019

# 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.)
1
Expert's answer
2017-02-24T14:50:04-0500
#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;
}

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 first!

### Ask Your question

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS