C++ Program to Check Prime Number with Explanation
C++
Medium
Control Flow
41 views
1 min read
164 words
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around prime, check, checking. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Check if number is prime (only divisible by 1 and itself).
Real Life: Like checking if you can divide chocolates equally in groups.
Input Format
An integer N.
Output Format
Print
• Prime Number
OR
• Not a Prime Number
Constraints
• N ≥ 1
• Efficient checking (up to √N)
Concept Explanation
A prime number is divisible only by 1 and itself.
If a number can be divided evenly by any other number, it is not prime.
Step-by-Step Logic
1.Take the number N.
2.If N ≤ 1, it is not prime.
3.Loop from 2 to √N.
4.If N % i == 0 for any i:
• Number is not prime.
5.If no divisor is found:
• Number is prime.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
void control_q9_prime_check() {
int number = 29;
bool isPrime = true;
if(number <= 1) {
isPrime = false;
} else {
for(int i = 2; i * i <= number; i++) {
if(number % i == 0) {
isPrime = false;
break; // Found divisor, no need to check more
}
}
}
if(isPrime) {
cout << number << " is a Prime number" << endl;
} else {
cout << number << " is NOT a Prime number" << endl;
}
}
Common Mistakes
- Treating 1 as prime.
- Checking divisibility up to n instead of sqrt(n).
- Missing negative/zero inputs handling.
Solution Guide
Problem
Check if number is prime (only divisible by 1 and itself).
Real Life: Like checking if you can divide chocolates equally in groups.
Input / Output
Output
Print
• Prime Number
OR
• Not a Prime Number
Constraints
• N ≥ 1
• Efficient checking (up to √N)
Explanation
Concept Explanation
A prime number is divisible only by 1 and itself.
If a number can be divided evenly by any other number, it is not prime.
Step-by-Step Explanation
1.Take the number N.
2.If N ≤ 1, it is not prime.
3.Loop from 2 to √N.
4.If N % i == 0 for any i:
• Number is not prime.
5.If no divisor is found:
• Number is prime.
Details
Common Mistakes
- Treating 1 as prime.
- Checking divisibility up to n instead of sqrt(n).
- Missing negative/zero inputs handling.
Official Solution
void control_q9_prime_check() {
int number = 29;
bool isPrime = true;
if(number <= 1) {
isPrime = false;
} else {
for(int i = 2; i * i <= number; i++) {
if(number % i == 0) {
isPrime = false;
break; // Found divisor, no need to check more
}
}
}
if(isPrime) {
cout << number << " is a Prime number" << endl;
} else {
cout << number << " is NOT a Prime number" << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!