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

This program checks whether a given number is prime. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This program demonstrates efficient prime checking using the square root optimization, which is a fundamental algorithm in number theory and computer science.

---

1. What is a Prime Number?

A prime number is a natural number greater than 1 that:

Is divisible only by 1 and itself
Has exactly two distinct positive divisors

Examples of prime numbers:

-

2

(smallest prime, only even prime)

-

3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...

Examples of non-prime (composite) numbers:

-

4

(divisible by 1, 2, 4)

-

6

(divisible by 1, 2, 3, 6)

-

8

(divisible by 1, 2, 4, 8)

-

9

(divisible by 1, 3, 9)

-

1

(not prime, only one divisor)

Special cases:

-

1

is NOT prime (only one divisor)

-

2

is the only even prime number

All other even numbers (>2) are composite

Applications:

Cryptography (RSA encryption)
Hash functions
Random number generation
Mathematical research
Computer security

---

2. Header Files Used

#include <iostream>

Provides cout for output and cin for input

#include <cmath>

Provides sqrt() function
Used for the square root optimization

---

3. Declaring Variables

int num;

bool isPrime = true;

Variable `num`:

Stores the number to check for primality

Variable `isPrime`:

Boolean flag indicating if number is prime

-

Initialized to `true`

we assume prime until proven otherwise
Will be set to false if we find a divisor

Why initialize to `true`?

We start assuming the number is prime
If we find any divisor (other than 1 and itself), we set it to false
If no divisors found, it remains true

---

4. Taking Input From User

`cout << "Enter a number: ";`

cin >> num;

Prompts user to enter a number
Reads and stores it

Example:

User enters:

17

num = 17

---

5. Checking Edge Cases

if (num <= 1)

isPrime = false;

Why check for num <= 1?

Numbers ≤ 1 are NOT prime by definition

-

1

has only one divisor (itself)

-

0 and negative numbers

are not prime

What happens:

If num <= 1, set isPrime = false
Skip the loop (no need to check divisors)
Go directly to output

Examples:

num = 1isPrime = false
num = 0isPrime = false
num = -5isPrime = false

---

6. The Square Root Optimization

for (int i = 2; i <= sqrt(num); i++)

Why only check up to √n?

Key mathematical insight:

If n has a divisor greater than √n, it must also have a divisor less than √n
Example: For n = 36
Divisors: 1, 2, 3, 4, 6, 9, 12, 18, 36
√36 = 6
If we check 2, 3, 4, 6 and find divisors, we don't need to check 9, 12, 18
They are just the "other half" of factor pairs

Efficiency comparison:

Naive approach (checking 2 to n-1):

For n = 100: Check 2, 3, 4, ..., 99 (98 checks)
Time complexity: O(n)

Optimized approach (checking up to √n):

For n = 100: Check 2, 3, 4, ..., 10 (9 checks)
Time complexity: O(√n)

-

Much faster!

---

7. Checking for Divisors

if (num % i == 0)

isPrime = false;

break;

What this does:

Checks if i divides num evenly (no remainder)
If num % i == 0, then i is a divisor
If we find any divisor (other than 1 and num), number is NOT prime
Set isPrime = false
break; exits loop immediately (no need to check further)

Why use `break;`?

Once we find a divisor, we know the number is composite
No need to continue checking
Saves time and improves efficiency

---

8. Step-by-Step Example

Example 1: Checking if 17 is prime

Step 1: Edge case check

17 <= 1

false

→ continue

Step 2: Loop through potential divisors

Check up to √17 ≈ 4.12, so check i = 2, 3, 4

Iteration 1 (i = 2):

17 % 2 == 01 == 0

false

Continue

Iteration 2 (i = 3):

17 % 3 == 02 == 0

false

Continue

Iteration 3 (i = 4):

17 % 4 == 01 == 0

false

Continue

Step 3: Result

Loop completes without finding divisors
isPrime remains true

-

17 is prime

Example 2: Checking if 15 is prime

Step 1: Edge case check

15 <= 1

false

→ continue

Step 2: Loop

Check up to √15 ≈ 3.87, so check i = 2, 3

Iteration 1 (i = 2):

15 % 2 == 01 == 0

false

Continue

Iteration 2 (i = 3):

15 % 3 == 00 == 0

true

isPrime = false
break; → exit loop

Step 3: Result

Divisor found (3)
isPrime = false

-

15 is not prime

---

9. Visual Representation

Checking 17 (Prime):

Check divisors from 2 to √17 (≈4.12):

i = 2: 17 % 2 = 1 ≠ 0 → Continue
i = 3: 17 % 3 = 2 ≠ 0 → Continue
i = 4: 17 % 4 = 1 ≠ 0 → Continue

No divisors found → Prime ✅

Checking 15 (Composite):

Check divisors from 2 to √15 (≈3.87):

i = 2: 15 % 2 = 1 ≠ 0 → Continue
i = 3: 15 % 3 = 0 = 0 → Found divisor!

Divisor found → Not prime ❌

---

10. Why This Algorithm is Efficient

For large numbers:

Checking if 10,000 is prime:
Naive: Check 2, 3, 4, ..., 9,999 (9,998 checks)
Optimized: Check 2, 3, 4, ..., 100 (99 checks)

-

100x faster!

Time complexity:

Naive: O(n)
Optimized: O(√n)
For n = 1,000,000: √n = 1,000 (1000x improvement!)

---

11. Displaying the Result

If prime:

cout << num << " is a prime number" << endl;

If not prime:

cout << num << " is not a prime number" << endl;

Examples:

Input: 17 → Output:

"17 is a prime number"

Input: 15 → Output:

"15 is not a prime number"

---

12. Special Cases

Case 1: Number 2

2 is prime (only even prime)
√2 ≈ 1.41, loop doesn't execute (i starts at 2)
isPrime remains true

Case 2: Even numbers > 2

All divisible by 2
First iteration (i = 2) finds divisor
Immediately set isPrime = false

Case 3: Perfect squares

Example: 25 = 5²
When i = 5: 25 % 5 == 0 → found divisor ✅

---

Summary

Prime number has exactly two divisors: 1 and itself
Check only up to √n for efficiency (square root optimization)
Use break; to exit early when divisor is found
Handle edge cases: numbers ≤ 1 are not prime
Time complexity: O(√n) - much better than O(n)

This program teaches:

Efficient algorithm design
Square root optimization technique
Boolean flags for state tracking
Early exit optimization (break;)
Number theory concepts

Understanding prime checking helps in:

Cryptography and security
Competitive programming
Mathematical problem solving
Many real-world applications

Prime numbers are fundamental in mathematics and computer science, and this efficient checking algorithm is used in many applications, from cryptography to number theory research.

Let us now understand every line and the components of the above program.

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.

Practical Learning Notes for Prime Check

This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents