Bird
Raised Fist0
DSA C++programming

Check if Number is Prime in DSA C++

Choose your learning style10 modes available
Mental Model
A prime number is a number greater than 1 that has no divisors other than 1 and itself. To check if a number is prime, we try dividing it by smaller numbers to see if any divide evenly.
Analogy: Imagine you have a box of candies and want to split them evenly among friends. If you can only split them evenly by giving all to one friend or keeping them all yourself, the number of candies is prime.
Number: 7
Try dividing by: 2, 3, 4, 5, 6
No exact division -> prime

7
↑ Check divisors -> 2,3,...6
No divisor found
Dry Run Walkthrough
Input: Check if number 7 is prime
Goal: Determine if 7 has any divisor other than 1 and 7
Step 1: Check division by 2
7 (number) -> divisor 2 -> 7 % 2 = 1 (not zero)
Why: 2 is the smallest divisor to test; if divides evenly, number is not prime
Step 2: Check division by 3
7 (number) -> divisor 3 -> 7 % 3 = 1 (not zero)
Why: Continue checking next divisor to find any exact division
Step 3: Check division by 4
7 (number) -> divisor 4 -> 7 % 4 = 3 (not zero)
Why: No divisor found yet, keep checking
Step 4: Check division by 5
7 (number) -> divisor 5 -> 7 % 5 = 2 (not zero)
Why: Still no divisor, continue
Step 5: Check division by 6
7 (number) -> divisor 6 -> 7 % 6 = 1 (not zero)
Why: No divisor found up to number-1, conclude prime
Result:
7 is prime
Annotated Code
DSA C++
#include <iostream>
#include <cmath>

bool isPrime(int n) {
    if (n <= 1) return false; // numbers <=1 are not prime
    int limit = static_cast<int>(std::sqrt(n));
    for (int i = 2; i <= limit; i++) {
        if (n % i == 0) {
            return false; // found divisor, not prime
        }
    }
    return true; // no divisors found, prime
}

int main() {
    int number = 7;
    if (isPrime(number)) {
        std::cout << number << " is prime" << std::endl;
    } else {
        std::cout << number << " is not prime" << std::endl;
    }
    return 0;
}
if (n <= 1) return false; // numbers <=1 are not prime
handle numbers that are not prime by definition
int limit = static_cast<int>(std::sqrt(n));
only check divisors up to square root of n to reduce work
for (int i = 2; i <= limit; i++) {
iterate through possible divisors from 2 to sqrt(n)
if (n % i == 0) {
check if i divides n exactly, meaning n is not prime
return false; // found divisor, not prime
stop early if divisor found
return true; // no divisors found, prime
if loop finishes, n is prime
OutputSuccess
7 is prime
Complexity Analysis
Time: O(√n) because we only check divisors up to the square root of n
Space: O(1) because only a few variables are used regardless of input size
vs Alternative: Naive approach checks all numbers up to n-1 with O(n) time, which is slower for large n
Edge Cases
number is 1 or less
returns false immediately because 1 and below are not prime
DSA C++
if (n <= 1) return false; // numbers <=1 are not prime
number is 2 (smallest prime)
returns true because 2 has no divisors other than 1 and itself
DSA C++
for (int i = 2; i <= limit; i++) {
number is a perfect square (e.g., 9)
detects divisor at sqrt(n) and returns false
DSA C++
if (n % i == 0) {
When to Use This Pattern
When you need to check if a number has no divisors other than 1 and itself, use the prime check pattern by testing divisors up to the square root.
Common Mistakes
Mistake: Checking divisors up to n-1 instead of sqrt(n), causing unnecessary work
Fix: Limit divisor checks to sqrt(n) to improve efficiency
Mistake: Not handling numbers less than or equal to 1 correctly
Fix: Add a condition to return false for n <= 1
Summary
Checks if a number is prime by testing divisors up to its square root.
Use when you need to quickly determine if a number is prime.
Only divisors up to the square root need to be checked to confirm primality.

Practice

(1/5)
1. What does it mean if a number is prime?
easy
A. It has exactly two distinct positive divisors: 1 and itself.
B. It is divisible by 2 only.
C. It is an even number greater than 2.
D. It has more than two divisors.

Solution

  1. Step 1: Understand the definition of prime number

    A prime number is a number greater than 1 that has no divisors other than 1 and itself.
  2. Step 2: Compare options with definition

    Only It has exactly two distinct positive divisors: 1 and itself. correctly states that a prime number has exactly two distinct positive divisors: 1 and itself.
  3. Final Answer:

    It has exactly two distinct positive divisors: 1 and itself. -> Option A
  4. Quick Check:

    Prime number = two divisors [OK]
Hint: Prime means divisible only by 1 and itself [OK]
Common Mistakes:
  • Thinking all even numbers are prime
  • Confusing prime with odd numbers
  • Assuming 1 is prime
2. Which of the following C++ code snippets correctly checks if a number n is prime?
easy
A. for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true;
B. for (int i = 2; i <= n; i++) { if (n % i == 0) return false; } return true;
C. for (int i = 1; i < n; i++) { if (n % i == 0) return false; } return true;
D. for (int i = 2; i < n/2; i++) { if (n % i == 0) return true; } return false;

Solution

  1. Step 1: Analyze loop range for prime check

    We check divisors from 2 up to but not including n to find any divisor.
  2. Step 2: Check correctness of each option

    for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; correctly checks divisors from 2 to n-1 and returns false if divisible, else true. for (int i = 2; i <= n; i++) { if (n % i == 0) return false; } return true; incorrectly includes n itself, causing false negatives. for (int i = 1; i < n; i++) { if (n % i == 0) return false; } return true; starts from 1, which divides all numbers. for (int i = 2; i < n/2; i++) { if (n % i == 0) return true; } return false; returns true on first divisor found, which is incorrect logic.
  3. Final Answer:

    for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; -> Option A
  4. Quick Check:

    Loop from 2 to n-1 and check divisibility [OK]
Hint: Check divisors from 2 to n-1 only [OK]
Common Mistakes:
  • Checking divisibility by 1 or n itself
  • Looping beyond n
  • Returning true too early
3. What is the output of the following C++ code?
int n = 11;
bool isPrime = true;
for (int i = 2; i <= n / 2; i++) {
    if (n % i == 0) {
        isPrime = false;
        break;
    }
}
std::cout << (isPrime ? "Prime" : "Not Prime") << std::endl;
medium
A. Runtime Error
B. Not Prime
C. Compilation Error
D. Prime

Solution

  1. Step 1: Understand the loop and condition

    The loop checks divisors from 2 to n/2 (which is 5 for n=11). It tests if 11 is divisible by any number in this range.
  2. Step 2: Check divisibility for each i

    11 % 2 != 0, 11 % 3 != 0, 11 % 4 != 0, 11 % 5 != 0. No divisor found, so isPrime remains true.
  3. Final Answer:

    Prime -> Option D
  4. Quick Check:

    11 has no divisors except 1 and itself [OK]
Hint: Check divisors only up to n/2 for efficiency [OK]
Common Mistakes:
  • Looping up to n instead of n/2
  • Not breaking loop on divisor found
  • Misinterpreting output
4. Find the error in this C++ code that checks if n is prime:
bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i < n; i++) {
        if (n % i == 0) return true;
    }
    return false;
}
medium
A. Loop should start from 1, not 2.
B. Returns true when a divisor is found, should return false instead.
C. Function should return true for n <= 1.
D. No error, code is correct.

Solution

  1. Step 1: Analyze return values on divisor found

    The code returns true immediately when a divisor is found, which means it claims the number is prime incorrectly.
  2. Step 2: Correct logic for prime check

    When a divisor is found, the function should return false (not prime). If no divisor is found, return true.
  3. Final Answer:

    Returns true when a divisor is found, should return false instead. -> Option B
  4. Quick Check:

    Return false on divisor found [OK]
Hint: Return false when divisor found, true otherwise [OK]
Common Mistakes:
  • Returning true on divisor found
  • Loop starting at 1
  • Not handling n <= 1 correctly
5. You want to optimize prime checking for large numbers by checking divisors only up to the square root of n. Which code snippet correctly implements this?
bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) return false;
    }
    return true;
}
hard
A. Incorrect: returns true inside the loop when divisor found.
B. Incorrect: loop should go up to n/2, not sqrt(n).
C. Correct: checks divisors up to sqrt(n) and returns false if divisible.
D. Incorrect: should start loop from 1 instead of 2.

Solution

  1. Step 1: Understand optimization using square root

    Any divisor larger than sqrt(n) pairs with a smaller divisor, so checking up to sqrt(n) is enough.
  2. Step 2: Verify code logic

    The loop runs from 2 to sqrt(n), returns false if divisor found, else true after loop ends. This is correct and efficient.
  3. Final Answer:

    Correct: checks divisors up to sqrt(n) and returns false if divisible. -> Option C
  4. Quick Check:

    Check divisors up to sqrt(n) for efficiency [OK]
Hint: Check divisors only up to sqrt(n) for speed [OK]
Common Mistakes:
  • Looping up to n/2 instead of sqrt(n)
  • Starting loop at 1
  • Returning true inside loop on divisor found
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard