Check Prime Number

Check Prime Number

Medium C++ Control Flow 42 views
Explanation Complexity

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

Example

7
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 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.

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.

Input / Output Format

Input Format
An integer N.
Output Format
Print

• Prime Number
OR

• Not a Prime Number
Constraints
• N ≥ 1

• Efficient checking (up to √N)

Examples

Input:
7
Output:
Prime Number

Example Solution (Public)

C++
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;
    }
}

Official Solution Code

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;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.