Prime number

A prime number is an integer which is greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

The logic to check a number is prime or not is really simple. We only need to check if the given number is completely divisible by any other smaller number or not, but not by 1 and itself.

After taking input from the user, we have to run one loop up to half of the given number. Now the reason for running one loop up to half of the given number is because we know, a number can only be divisible by a number which is lesser than its half.

Inside the loop we have to check if the given number “num” is completely divisible by current number “i” or not, If yes then set the value of the variable i to num and terminate the loop here, if no then continue the loop.

Once the loop is completed or terminated control comes out of the loop, here we have to check if the value of the variable i is equivalent to the given number or not. If yes then it is not a Prime number otherwise it is a prime number.

Program

#include <iostream>

using namespace std;

int main() {

    int i, num;

    // Take input from user
    cout << "Enter any number : ";
    cin >> num;

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

        if((num % i) == 0) {
            i = num;
            break;
        }
    }


    if(i == num) {
        cout << endl << num << " is not a prime number.";

    } else {
        cout << endl << num << " is a prime number.";
    }

    return 0;
}

Output

Enter any number : 7
7 is a prime number.