prime number program c++

#include <iostream>

bool isPrime(int number) {
    if(number <= 1)
        return false;
    for(int i=2; i*i<=number; i++) {
        if(number % i == 0)
            return false;
    }
    return true;
}

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;
    if(isPrime(num))
        std::cout << num << " is a prime number." << std::endl;
    else
        std::cout << num << " is not a prime number." << std::endl;
    return 0;
}

This is a C++ program that determines whether a given number is prime or not.

Explanation:

  • The program begins by including the iostream header file, which is necessary for input/output operations.

  • The isPrime function is defined to determine whether a number is prime or not. It takes an integer number as input and returns a boolean value (true if the number is prime, false otherwise).

  • Inside the isPrime function, the first condition checks if the number is less than or equal to 1. If it is, the function immediately returns false, as prime numbers are defined to be greater than 1.

  • The second part of the isPrime function is a for loop that iterates from 2 to the square root of the input number (i*i<=number). This is because if there is a factor of the number greater than its square root, there must be a corresponding factor smaller than the square root.

  • Inside the loop, the condition number % i == 0 checks if number is divisible by i. If it is, the function immediately returns false, as it means the number is not prime.

  • If the loop completes without finding any factors, the function returns true, indicating that the number is prime.

  • In the main function, an integer variable num is declared to store the user input.

  • The program prompts the user to enter a number using std::cout and reads the input using std::cin.

  • The isPrime function is called with the input number as an argument, and the result is used to determine whether the number is prime or not.

  • Finally, the program outputs the result using std::cout based on the return value of the isPrime function.

  • The program ends by returning 0 from the main function, indicating successful execution.