Prime Check

Program to check if a number is prime

BeginnerTopic: Loop Programs
Back

C++ Prime Check Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int num;
    bool isPrime = true;
    
    cout << "Enter a number: ";
    cin >> num;
    
    if (num <= 1) {
        isPrime = false;
    } else {
        for (int i = 2; i <= sqrt(num); i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }
    }
    
    if (isPrime) {
        cout << num << " is a prime number" << endl;
    } else {
        cout << num << " is not a prime number" << endl;
    }
    
    return 0;
}
Output
Enter a number: 17
17 is a prime number

Understanding Prime Check

A prime number is only divisible by 1 and itself. We check divisibility from 2 to √n (square root optimization). If any number divides it, it's not prime. We only need to check up to √n because if a factor exists, one must be ≤ √n.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents