Answer to Question #152426 in C++ for Usama Saleem

Question #152426
Write a program which takes as input and integer and prints "prime number" if it is a prime number. Hint: Suppose the number is 7 - divide it by 2 then 3 then 4 then 5 then 6 - if in any division, the remainder is zero, that means the number is not a prime.
1
Expert's answer
2020-12-23T13:12:48-0500
#include <iostream> //std::cin, std::cout
#include <cmath> //sqrt

int main()
{
    //read the number
    int number;
    std::cin >> number;
    
    //check if number is prime
    bool prime = true;
    
    //to do this we must go through all numbers
    //not greater than square root of initial number
    int root = (int)sqrt(number);
    
    for (int den = 2; den <= root; den++)
        if (number % den == 0)
        {
            prime = false;
            break;
        }
    
    //print "prime number" if number is prime
    if (prime)
        std::cout << "prime number" << std::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