Answer to Question #125070 in C++ for Zeeshan Ali

Question #125070
: Write 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
2020-07-03T09:48:49-0400
#include <iostream>


int main()
{
    std::cout << "Please input a positive integer: ";
    int number;
    std::cin >> number;


    if(number < 0)
    {
        std::cout << "Error: integer is negative\n";
        return 1;
    }


    if(number < 2)
    {
        std::cout << "Integer is not prime\n";
        return 0;
    }


    if(number == 2)
    {
        std::cout << "Integer is prime\n";
        return 0;
    }


    if(number % 2 == 0)
    {
        std::cout << "Integer is not prime\n";
        return 0;
    }


    for(int i=3; (i*i)<=number; i+=2)
    {
        if(number % i == 0)
        {
            std::cout << "Integer is not prime\n";
            return 0;
        }
    }


    std::cout << "Integer is prime\n";
    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