Check for Prime Number in C++

This program checks if a given number is prime.

#include <iostream>

int main() {

    int n, i;

    bool isPrime = true;

 

    std::cout << "Enter a positive integer: ";

    std::cin >> n;

 

    if (n == 0 || n == 1) {

        isPrime = false;

    } else {

        for (i = 2; i <= n / 2; ++i) {

            if (n % i == 0) {

                isPrime = false;

                break;

            }

        }

    }

 

    if (isPrime)

        std::cout << n << " is a prime number." << std::endl;

    else

        std::cout << n << " is not a prime number." << std::endl;

 

    return 0;

}

No comments:

Post a Comment

MS Excel Logical Functions

Logical functions in Excel are powerful tools that help you make decisions based on conditions. Whether you're comparing values or testi...

Post Count

Loading...