Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Check if a Number is Prime or Not | GFG
    Data Structures & Algorithms

    Check if a Number is Prime or Not | GFG

    Anirudh KhuranaBy Anirudh Khurana29 June 2025Updated:16 November 2026No Comments7 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to check if a number is prime or not
    Share
    Facebook Twitter LinkedIn Pinterest Email

    A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
    Formally, n is prime ⇔ it cannot be written as a × b where a > 1 and b > 1.

    Why this matters:

    • Prime testing is foundational in number theory, cryptography (RSA keys!), hashing, random-number generators, and countless coding interview puzzles.
    • Writing progressively faster primality checks trains your ability to reason about loops, divisors, and mathematical bounds.

    Here’s the [Problem Link] to begin with.

    Quick Examples

    nOutputExplanation
    2TrueOnly divisors are 1 and 2.
    4FalseDivisible by 2.
    17TrueNo divisor other than 1 and 17 itself.
    1FalseBy definition, 1 is not prime.

    In the following sections we’ll build three increasingly efficient solutions.

    Interactive Visualizer: Trial Division up to √n

    Type any number up to 1,000,000,000 and press Next to see which divisors get tested. The bars compare how many loop iterations each of the three methods in this post needs for the same number.



    Brute Force Solution

    Intuition & Approach

    The most straightforward idea is:

    1. Edge Case: 1 is not prime.
    2. Try every integer i from 2 up to n-1.
    3. If any i divides n evenly (n % i == 0), n is composite; otherwise it’s prime.

    Code Implementation

    class Solution:
        def isPrime(self, n):
            if n == 1:                      # 1 is not prime
                return False
            # test every possible divisor from 2 up to n-1
            for i in range(2, n):
                if n % i == 0:              # found a divisor → not prime
                    return False
            return True                     # no divisors found → prime
    class Solution {
        static boolean isPrime(int n) {
            if (n == 1) return false;          // 1 is not prime
            // test every possible divisor from 2 up to n-1
            for (int i = 2; i < n; i++) {
                if (n % i == 0) return false;  // found a divisor → not prime
            }
            return true;                       // no divisors found → prime
        }
    }
    class Solution {
    public:
        bool isPrime(int n) {
            if (n == 1) return false;          // 1 is not prime
            // test every possible divisor from 2 up to n-1
            for (int i = 2; i < n; i++) {
                if (n % i == 0) return false;  // found a divisor → not prime
            }
            return true;                       // no divisors found → prime
        }
    };

    Code Explanation

    • The for loop exhaustively checks all potential divisors.
    • Early exit on the first successful division saves some time, but worst-case still touches every number below n.

    Dry Run (n = 10)

    1. i=2 → 10 % 2 == 0 → returns False.
    2. Loop stops immediately.

    Time & Space Complexity

    • Time: O(n) (linear in n).
    • Space: O(1) – constant auxiliary memory.

    Conclusion

    Elegant in its simplicity, but painfully slow for large numbers (think millions or cryptographic bit-lengths).


    Better Solution (Half-Range Check)

    Intuition & Approach

    A composite number must have at least one factor ≤ n/2.
    Therefore we only need to test divisors up to ⌊n/2⌋.

    Code Implementation

    class Solution:
        def isPrime(self, n):
            if n == 1:                      # still not prime
                return False
            # any factor bigger than n//2 leaves a co-factor < 2
            for i in range(2, n // 2 + 1):
                if n % i == 0:              # divisor found
                    return False
            return True
    class Solution {
        static boolean isPrime(int n) {
            if (n == 1) return false;          // still not prime
            // any factor bigger than n/2 leaves a co-factor < 2
            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) return false;  // divisor found
            }
            return true;
        }
    }
    class Solution {
    public:
        bool isPrime(int n) {
            if (n == 1) return false;          // still not prime
            // any factor bigger than n/2 leaves a co-factor < 2
            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) return false;  // divisor found
            }
            return true;
        }
    };

    Code Explanation

    • Reduces the divisor range roughly by half, yet retains the same early-exit behavior.

    Dry Run (n = 15)

    Divisor loop iterates i = 2 … 7; finds i = 3 quickly, returns False.

    Time & Space Complexity

    • Time: O(n/2) → still expressed as O(n) (constants dropped).
    • Space: O(1).

    Conclusion

    A modest improvement; still far from efficient when n is large.


    Optimal Solution (Square-Root Bound)

    Intuition & Approach

    If n is composite, it can be factored into a × b = n.
    At least one factor a ≤ √n.
    So it suffices to test divisors only up to ⌊√n⌋.

    Code Implementation

    class Solution:
        def isPrime(self, n):
            if n == 1:                          # handle 1
                return False
            # only test up to √n
            for i in range(2, int(n ** 0.5) + 1):
                if n % i == 0:                  # divisor within √n found
                    return False
            return True                         # prime if loop finishes
    class Solution {
        static boolean isPrime(int n) {
            if (n == 1) return false;              // handle 1
            // only test up to √n (i * i <= n avoids floating point)
            for (long i = 2; i * i <= n; i++) {
                if (n % i == 0) return false;      // divisor within √n found
            }
            return true;                           // prime if loop finishes
        }
    }
    class Solution {
    public:
        bool isPrime(int n) {
            if (n == 1) return false;              // handle 1
            // only test up to √n (i * i <= n avoids floating point)
            for (long long i = 2; i * i <= n; i++) {
                if (n % i == 0) return false;      // divisor within √n found
            }
            return true;                           // prime if loop finishes
        }
    };

    Code Explanation

    • The loop bound int(n ** 0.5) + 1 computes the floor of √n and includes it.
    • Once past that limit, any remaining divisor would pair with one below the limit, which we’d have already checked.

    Dry Run (n = 29)

    • √29 ≈ 5.38 → test i = 2,3,4,5.
    • None divide evenly → returns True.
      (Brute force would have checked up to 28.)

    Time & Space Complexity

    • Time: O(√n) – a dramatic speedup, especially for big inputs.
    • Space: O(1).

    Conclusion

    Using the square-root insight slashes runtime from linear to sub-linear, transforming primality testing into a practically instantaneous task for medium-sized integers. For industrial-strength cryptography you’d employ even faster algorithms (e.g., Miller–Rabin), but for typical interview constraints this √n approach is optimal and elegant.


    Key Takeaways

    1. Start simple, verify correctness, then refine the bounds.
    2. Cutting the search space from n → n/2 → √n shows the power of mathematical reasoning.
    3. These same bounding ideas generalize to many divisor-based and search problems.

    Now you’re equipped with three tiers of prime-checking solutions, ready for anything from classroom exercises to tech-interview whiteboards!

    Frequently Asked Questions

    How do you check if a number is prime?

    Try dividing it by every whole number from 2 up to its square root. If none of them divides it evenly, the number is prime. For example, 97 is prime because none of 2 to 9 divides it, while 91 is not prime because 91 = 7 × 13.

    Why is it enough to check divisors up to √n?

    If n = a × b and both a and b were bigger than √n, their product would be bigger than n. So every composite number has at least one divisor that is less than or equal to √n.

    Is 1 a prime number? What about 0 and 2?

    1 is not prime because a prime must have exactly two divisors, 1 and itself. 0 is not prime either. 2 is prime, and it is the only even prime number.

    What is the time complexity of checking a prime number?

    The square-root method runs in O(√n) time and O(1) space. The brute force method that tries every number up to n−1 is O(n), and the half-range method is O(n/2), which is still O(n).

    What is the fastest way to find many prime numbers?

    To test one number, trial division up to √n is enough. To find all primes up to a limit, use the Sieve of Eratosthenes, which marks multiples of each prime and runs in O(n log log n).


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Easy Math
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous Article4Sum | Leetcode 18 | Explained in Python
    Next Article Print N times with Recursion | GFG
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (2)
    Recent Posts

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.