Check Prime Number in Python

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. Examples: 2, 3, 5, 7, 11. Non-examples: 1, 4, 9, 15. This tutorial covers trial division up to sqrt(n), a live checker, worked Python examples, edge cases, and complexity.

Definition

n > 1

Only divisors are 1 and n.

Guard < 2

Not prime

1, 0, negatives fail first.

Trial Divide

i*i <= n

Stop at sqrt(n) safely.

Only Even Prime

2

All larger evens are composite.

Live Preview

Try 17 / 18

See verdict and reason.

vs Composite

n > 1

Composite = not prime (and > 1).

Introduction

A prime number is an integer greater than 1 that has no positive divisors other than 1 and itself. So 17 is prime, while 15 = 3 × 5 is not.

Interviews almost always want trial division: reject n < 2, then test candidates while i * i <= n. One found factor proves composite; surviving the loop proves prime.

Why it matters?

It is the most common number-theory interview check and the foundation for sieves, factorization, and cryptography warm-ups.

Key Highlights

n > 1

1 is not prime.

Sqrt Bound

i*i <= n is enough.

2 Is Special

Only even prime.

O(√n)

Interview complexity.

In short: guard n < 2, then trial divide while i * i <= n.

📝 Problem & Approach

Given an integer n, return whether it is prime.

python
# 17 -> prime   (no divisor up to sqrt(17))
# 15 -> not     (3 divides 15)
# 2  -> prime   (smallest / only even)
# 1  -> not     (primes start at 2)

Inputs & Outputs

ItemTypeDescription
nintValue to classify.
ReturnboolTrue when n is prime.
Key boundloopwhile i * i <= n

Minimal workflow

Pseudocode
function isPrime(n):
    if n < 2:
        return false
    for i from 2 while i * i <= n:
        if n mod i = 0:
            return false
    return true

Method comparison

MethodIdeaNotes
Trial to sqrtTest i while i*i <= nInterview default
Skip evensHandle 2, then odd i onlyFaster constant factors
SieveMark composites up to NBest for many primes

⚡ Quick Reference

GoalPattern
Reject smallif n <= 1: return False
Sqrt loopwhile i * i <= n:
Composite hitif n % i == 0: return False
Primereturn True
Skip evensif n % 2 == 0: …; i += 2
Interview lineGuard n < 2, trial to sqrt(n), O(sqrt(n))

📋 Trial vs Odds vs Sieve

Same question — pick the right tool.

Trial sqrt
i*i <= n

Clearest single-check answer

Odd divisors
i += 2

Same idea, fewer loops

Sieve
mark up to N

Many primes, one pass

vs factors
stop early

Prime check exits on first hit

Context

When This Problem Shows Up

Reach for a primality check whenever you need a true/false for “is n prime?”

  1. Interview classics

    Nearly every number-theory warm-up.

  2. Range listing

    Print primes inside [a, b].

  3. Bridge to factors

    Same divisor thinking as factorization.

  4. Teaching sqrt bound

    Why i*i <= n is enough.

  5. Not for huge bulk

    Use a sieve when listing many primes.

Key benefit: one short helper that teaches guards, sqrt reasoning, and O(sqrt(n)) analysis in one shot.

🔮 Live Preview

Follows the same algorithm as the Python function: handle small values, then test divisors while i * i <= n.

Use an integer. Preview input is capped to keep browser checks fast.

Live result
Press “Run check” to classify n.

Examples Gallery

Three complete Python programs — check 17, list primes from 1 to 20, and a faster odd-divisor variant. Click View Output to reveal sample console results.

📚 Getting Started

The classic interview helper with a sqrt bound.

Example 1 — Check a Single Number

Handles n <= 1, then checks divisors only up to sqrt(n).

python
def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True


test_number = 17
if is_prime(test_number):
    print(f"{test_number} is a prime number.")
else:
    print(f"{test_number} is not a prime number.")

How It Works

For 17, candidates run while i * i <= 17 (i = 2, 3, 4). None divides 17, so the function returns True.

⚡ Listing Primes

Reuse the helper across a small interval.

Example 2 — Prime Numbers Between 1 and 20

Reuse is_prime() and print primes in a small interval.

python
def is_prime(num: int) -> bool:
    if num <= 1:
        return False
    i = 2
    while i * i <= num:
        if num % i == 0:
            return False
        i += 1
    return True


start, end = 1, 20
print(f"Prime numbers in the range {start} to {end}:")
for value in range(start, end + 1):
    if is_prime(value):
        print(value, end=" ")
print()

How It Works

Each value from 1 to 20 is classified independently. 1 is rejected by the guard; composites fail on their first divisor.

Example 3 — Skip Even Divisors

Handle 2 specially, then test only odd candidates.

python
def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True


for value in (2, 17, 18, 1, 19):
    label = "prime" if is_prime(value) else "not prime"
    print(f"{value}: {label}")

How It Works

After rejecting even n > 2, the loop only needs odd i. That roughly halves the number of modulo checks.

🧠 How the Algorithm Decides

1

Handle small values

If n <= 1, it is not prime.

Guard
2

Try divisors

Loop i from 2 while i * i <= n.

Search
3

Fail on a hit

If n % i == 0, return False immediately.

Rule
=

Survive = prime

No divisor found up to sqrt(n).

🔎 Worked Walkthrough — 17 vs 15

Why the sqrt bound catches composites early and lets primes through.

ni checked (i*i <= n)Hit?Verdict
172, 3, 4NoPrime
152, then 3Yes (3)Not prime
2(loop does not run)Prime
1guardNot prime

If n = a * b with a, b > 1, at least one factor is <= sqrt(n) — so the loop is enough.

Use Cases

Where prime checks show up beyond the interview prompt.

1. Interview Classics

Guards + sqrt trial division.

Example: is_prime(17).

2. Range Filters

List primes in a band.

Example: 1..20 list.

3. After Factorization

Same divisor mindset as factors.

Example: previous page.

4. Teaching 1 vs 2

Clarify neither/prime edge cases.

Example: live preview.

5. Odd-Only Upgrade

Mention when asked about speed.

Example: Example 3.

6. Next: Pronic

Continue the interview chain.

Example: related CTA.

Pro Tip: open with “Guard n < 2, then trial divide up to sqrt(n), so time is O(sqrt(n)).”

Advantages

Why trial division works well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 15 and 17 on paper quickly.

  2. 2. Clear Complexity

    O(sqrt(n)) is easy to justify.

  3. 3. Early Exit

    Composites often fail on the first factor.

  4. 4. Upgrade Path

    Skip evens or mention sieves later.

Pro Tip: lead with the simple sqrt loop; offer odd-only or sieve only if asked about speed or bulk queries.

Usage Tips

Small habits that keep prime checks interview-ready.

  1. 1. Guard n <= 1

    Never skip the small-value check.

  2. 2. Use i*i <= n

    Avoid float sqrt if you can.

  3. 3. Name 2 Explicitly

    Only even prime — interviewers like hearing it.

  4. 4. Early Return

    Exit as soon as a divisor appears.

  5. 5. Sieve for Bulk

    Do not trial-divide every n up to huge N.

Pro Tip: sanity-check 1, 2, 17, and 15 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break prime-number programs.

  1. 1. Calling 1 Prime

    1 has only one positive divisor.

    → Return False for n <= 1.

  2. 2. Looping to n - 1

    Unnecessary and slow.

    → Stop at i * i <= n.

  3. 3. Trusting Float sqrt Alone

    Rounding can mis-bound the loop.

    → Prefer i * i <= n.

  4. 4. Accepting Negatives

    Primality is for integers > 1.

    → Treat negatives as not prime.

  5. 5. Trial for Huge Ranges

    Checking every n to millions one-by-one.

    → Use a sieve for bulk listing.

Edge Cases

Handle these before claiming the check is complete.

n = 1

Not prime

Neither prime nor composite.

n = 2

Prime

Smallest and only even prime.

Even > 2

Composite

Divisible by 2.

Negative

Not prime

Definition starts above 1.

17

Classic yes

No divisor up to sqrt(17).

15

Classic no

Caught by factor 3.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Sqrt proof. If n = a*b and both > sqrt(n), product exceeds n.
  • Infinitely many. There is no largest prime.
  • 2 alone. Every even number greater than 2 is composite.
  • 1 is special. Neither prime nor composite.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 17

  • Trace i = 2..4
  • Confirm True

2. Reject 15

  • Show factor 3
  • Early return

3. List 1..20

  • Reproduce Example 2
  • Eight primes

4. Skip evens

  • Implement Example 3
  • Match results

Notes

  • Definition: prime means n > 1 with no divisor other than 1 and n.
  • Optimization: trial division up to sqrt(n) is the key speedup.
  • Skip evens: handle 2 first, then test only odd divisors.
  • For lots of primes up to N, use a sieve. Trial division is best for simple one-off checks. Interview line: guard n < 2, trial to sqrt(n), O(sqrt(n)).

Quick Takeaway: guard n < 2, then trial divide while i*i <= n.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Trial to sqrt(n)O(sqrt(n))O(1)
Range check [a, b]About O((b-a)*sqrt(b))O(1)
Sieve up to NO(N log log N)O(N)

For interview demos, quote O(sqrt(n)) for a single check and mention sieves for bulk listing.

Wrap Up

🎉 Conclusion

A prime is an integer greater than 1 with no divisor other than 1 and itself. Guard small values, trial divide up to sqrt(n), and remember that 2 is the only even prime.

Practice the three examples above, then continue to pronic numbers.

Guard n < 2, then trial divide while i*i <= n — that is the interview answer.

💡 Best Practices

✅ Do

  • Reject n <= 1 early
  • Loop while i * i <= n
  • Return False on first divisor
  • Treat 2 as the even special case
  • Quote O(sqrt(n)) clearly

❌ Don’t

  • Call 1 prime
  • Loop all the way to n
  • Rely only on float sqrt
  • Accept negatives as prime
  • Trial-divide huge ranges blindly

Key Takeaways

Knowledge Unlocked

Five things to remember about primes

Classify primality the interview-friendly way.

5
Core concepts
02

Bound

i*i <= n

Loop
2 03

Special

only even

Edge
1 04

Not

1 fails

Guard
O 05

Cost

O(√n)

Analysis

❓ Frequently Asked Questions

A prime is a whole number bigger than 1 that cannot be split into two smaller whole factors (except 1 times itself). Its only positive divisors are 1 and the number itself.
No. By the usual definition, primes start at 2. The number 1 has only one positive divisor, so it is neither prime nor composite.
Yes. It is the smallest and the only even prime.
If n = a*b and both a and b were larger than sqrt(n), then a*b would be larger than n. So any non-trivial factor must appear at or below sqrt(n).
Not for huge values, but it is the standard beginner and interview approach for single-number checks.
Primality is defined for integers greater than 1, so negatives are treated as not prime.
Call is_prime on each value and print the True cases.
Yes after handling 2 — test only odd i for a faster check.
When you need many primes up to a bound N, not for one-off checks.

Did you Know? 🔊

The only even prime is 2. Every integer greater than 1 is either prime or composite—except 1, which is neither. There are infinitely many primes.

Continue to Pronic Number

Learn how to check whether a number is pronic in Python.

Pronic number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful