Short answer: A prime number is a positive integer greater than 1 that has exactly two factors: 1 and the number itself. In Python, the simplest way to check whether a number is prime is to test whether any number from 2 up to its square root divides it evenly. This reduces the time complexity from O(n) to O(√n).
For example, 2, 3, 5, 7, 11, 13, 17 and 19 are prime numbers because they are divisible only by 1 and themselves.
Numbers such as 4, 6, 8, 9, 10 and 12 are not prime because they have additional factors.
Prime-number programs are among the most common beginner Python problems and frequently appear in coding interviews. They test your understanding of loops, conditions, operators, functions, optimization and time complexity.
In this guide, you will learn how to:
- Check whether a number is prime in Python
- Write a basic prime-number program
- Check divisors only up to √n
- Use Python’s
for...elsesyntax - Apply the 6k ± 1 optimization
- Generate all prime numbers within a range
- Use the Sieve of Eratosthenes
- Print prime numbers between two numbers
- Count prime numbers
- Find the next prime number
- Handle common edge cases
- Understand the time and space complexity of each approach
- Answer common prime-number interview questions
All examples are written for Python 3.
What Is a Prime Number?
A prime number is a whole number greater than 1 that has exactly two positive divisors:
- 1
- The number itself
For example:
2 → 1, 2
3 → 1, 3
5 → 1, 5
7 → 1, 7
11 → 1, 11
13 → 1, 13
Therefore, these are prime numbers.
In contrast:
4 → 1, 2, 4
6 → 1, 2, 3, 6
8 → 1, 2, 4, 8
9 → 1, 3, 9
10 → 1, 2, 5, 10
These numbers have more than two divisors, so they are composite numbers.
Is 1 a Prime Number?
No.
This is one of the most common interview questions.
The number 1 has only one positive divisor, which is 1 itself.
A prime number must have exactly two distinct positive divisors.
Therefore:
1 → Not prime
2 → Prime
3 → Prime
Is 0 a Prime Number?
No.
Zero is not prime because it does not have exactly two positive divisors.
Is 2 a Prime Number?
Yes.
2 is the smallest prime number and the only even prime number.
Every other even number is divisible by 2 and therefore has at least three positive divisors.
For example:
2 → Prime
4 → Not prime
6 → Not prime
8 → Not prime
10 → Not prime
Method 1: Basic Prime Number Program Using a Loop
The easiest approach is to check every number between 2 and n - 1.
def is_prime_basic(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
print(is_prime_basic(29))
Output:
True
The % operator returns the remainder after division.
If:
n % i == 0
then i divides n exactly.
For example:
29 % 2 → 1
29 % 3 → 2
29 % 4 → 1
...
29 % 28 → 1
No number divides 29 evenly, so 29 is prime.
How This Program Works
The function first checks:
if n < 2:
return False
This handles:
Negative numbers
0
1
None of these are prime.
Then:
for i in range(2, n):
checks every possible divisor between 2 and n - 1.
If a divisor is found:
if n % i == 0:
return False
the function immediately returns False.
If the loop finishes without finding a divisor:
return True
is executed.
Time Complexity
The basic approach takes:
O(n) time.
For a large number, this means a large number of divisibility checks.
For example, if you check a number close to one million, this method may perform nearly one million iterations.
It works correctly, but it is not the most efficient approach.
Method 2: Check Divisors Only Up to √n
A much better approach is to check possible divisors only up to the square root of the number.
Python provides math.isqrt() for calculating the exact integer square root.
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, math.isqrt(n) + 1):
if n % i == 0:
return False
return True
print(is_prime(97))
print(is_prime(1))
print(is_prime(91))
Output:
True
False
False
This is generally the recommended approach when you need to determine whether one number is prime.
Why Do We Check Only Up to √n?
Suppose:
n = a × b
If both a and b were greater than √n, their product would be greater than n.
Therefore, whenever a number has a factor other than 1 and itself, at least one of its factors must be less than or equal to √n.
Consider:
36 = 6 × 6
The square root of 36 is 6.
Or:
91 = 7 × 13
The square root of 91 is approximately 9.5.
Because 7 is less than √91, finding 7 is enough to establish that 91 is not prime.
There is no need to test 13 separately.
Why math.isqrt() Is Useful
You could write:
int(n ** 0.5)
but math.isqrt() is preferable when you need an exact integer square root.
It avoids relying on floating-point arithmetic and is designed specifically for integer square roots.
The loop:
range(2, math.isqrt(n) + 1)
includes the square root when it is an integer.
The + 1 is important.
Without it, perfect squares could be missed.
For example:
25 = 5 × 5
49 = 7 × 7
121 = 11 × 11
The divisor itself must be included.
Time Complexity
The square-root approach takes:
O(√n) time.
This is significantly faster than checking all numbers up to n.
For example, for a number around one million:
Basic method → roughly 1,000,000 checks
√n method → roughly 1,000 checks
That is why checking up to √n is the standard approach for testing one number.
Method 3: Prime Number Program Using for…else
Python has a useful feature called for...else.
The else block runs when the loop finishes normally without encountering a break.
Consider:
n = 37
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
print(n, "is not prime")
break
else:
print(n, "is prime")
Output:
37 is prime
If a divisor is found, break stops the loop and the else block does not execute.
If no divisor is found, the loop finishes normally and the else block runs.
Why Is for…else Useful in Interviews?
It demonstrates that you understand a Python-specific language feature.
However, it is important to explain what the else means.
It does not mean:
“Run this after every loop.”
It means:
“Run this if the loop finishes without a break.”
For example:
for i in range(2, 10):
if i == 5:
break
else:
print("Loop completed")
The else block does not execute because the loop was interrupted by break.
Method 4: Prime Number Using the 6k ± 1 Optimization
After checking 2 and 3, we can make the prime-checking algorithm more efficient by observing that every prime number greater than 3 must be of the form:
6k - 1
or:
6k + 1
Examples:
5 = 6(1) - 1
7 = 6(1) + 1
11 = 6(2) - 1
13 = 6(2) + 1
17 = 6(3) - 1
19 = 6(3) + 1
23 = 6(4) - 1
25 = 6(4) + 1
Notice that 25 fits the pattern but is not prime.
This is important.
The 6k ± 1 rule tells us which numbers can potentially be prime. It does not prove that every number in that form is prime.
A Python implementation is:
def is_prime_6k(n):
if n < 2:
return False
if n < 4:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
print(is_prime_6k(7919))
Output:
True
Why Does the 6k ± 1 Method Work?
Every integer can be represented as one of:
6k
6k + 1
6k + 2
6k + 3
6k + 4
6k + 5
Numbers in these groups have obvious divisibility properties:
6k → divisible by 2 and 3
6k + 2 → divisible by 2
6k + 3 → divisible by 3
6k + 4 → divisible by 2
That leaves:
6k + 1
6k + 5
Since:
6k + 5 = 6(k + 1) - 1
the candidates can be expressed as:
6k - 1
6k + 1
After eliminating multiples of 2 and 3, the algorithm checks only these candidates.
Time Complexity
The asymptotic complexity remains:
O(√n)
but it performs fewer divisibility checks than the basic √n method.
This is useful when an interviewer asks:
“Can you optimize your prime-number solution further?”
Method 5: Find All Prime Numbers Using the Sieve of Eratosthenes
If you need to find many prime numbers up to a particular limit, repeatedly calling is_prime() is not always the best approach.
The Sieve of Eratosthenes is a classic algorithm for generating all prime numbers up to a given limit.
import math
def sieve(limit):
is_p = [True] * (limit + 1)
is_p[0] = is_p[1] = False
for i in range(2, math.isqrt(limit) + 1):
if is_p[i]:
for j in range(i * i, limit + 1, i):
is_p[j] = False
return [i for i, p in enumerate(is_p) if p]
print(sieve(50))
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
How Does the Sieve Work?
Initially, every number is assumed to be prime:
2 3 4 5 6 7 8 9 10 ...
Starting with 2, mark all multiples of 2 as non-prime:
4, 6, 8, 10, 12...
Then move to 3 and mark:
6, 9, 12, 15...
Then 5:
10, 15, 20, 25...
You only need to perform this process for numbers up to √limit.
Why Start Marking at i × i?
Suppose:
i = 5
The multiples are:
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
But 10, 15 and 20 have already been marked by smaller prime numbers.
Therefore, the first new multiple that needs to be marked is:
5 × 5 = 25
This is why the inner loop starts with:
i * i
Sieve Complexity
The Sieve of Eratosthenes runs in approximately:
O(n log log n) time
and uses:
O(n) space.
It is an excellent choice when you need all primes up to a known limit.
How to Print Prime Numbers Between 1 and 100
One simple approach is to use the is_prime() function.
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
for n in range(1, 101):
if is_prime(n):
print(n, end=" ")
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
This approach is easy to understand and perfectly suitable for a beginner coding interview.
How to Print Prime Numbers Between Two Numbers
You can generalise the same approach to any range.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
start = 20
end = 50
for n in range(start, end + 1):
if is_prime(n):
print(n, end=" ")
Output:
23 29 31 37 41 43 47
Notice that end + 1 is used because Python’s range() excludes its upper limit.
How to Count Prime Numbers in a Range
Instead of printing the prime numbers, maintain a counter.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
count = 0
for n in range(1, 101):
if is_prime(n):
count += 1
print(count)
Output:
25
There are 25 prime numbers between 1 and 100.
How to Find the Next Prime Number
Sometimes an interviewer may ask you to find the first prime number greater than a given number.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def next_prime(n):
candidate = n + 1
while not is_prime(candidate):
candidate += 1
return candidate
print(next_prime(20))
Output:
23
The function starts with the next number and continues until it finds a prime.
How to Find the First N Prime Numbers
You can maintain a list of primes and continue checking numbers until the required count is reached.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def first_n_primes(n):
primes = []
number = 2
while len(primes) < n:
if is_prime(number):
primes.append(number)
number += 1
return primes
print(first_n_primes(10))
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
This is straightforward, although a sieve can be more appropriate when the upper limit is known.
Prime Number Program Using Recursion
Prime checking is naturally suited to iteration, but interviewers sometimes ask whether it can be implemented recursively.
def is_prime_recursive(n, divisor=2):
if n < 2:
return False
if divisor * divisor > n:
return True
if n % divisor == 0:
return False
return is_prime_recursive(n, divisor + 1)
print(is_prime_recursive(29))
Output:
True
Although this works, recursion is not necessarily better here.
For a simple prime-checking problem, an iterative solution is generally easier to read and avoids unnecessary recursive function calls.
Prime Number Program Without Using a Function
In beginner programming exercises, you may be asked to write the program directly without defining a function.
n = 29
is_prime = True
if n < 2:
is_prime = False
else:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
is_prime = False
break
if is_prime:
print("Prime")
else:
print("Not Prime")
Output:
Prime
This version is useful when practising basic Python syntax.
In production code, however, wrapping the logic in a function usually makes it easier to reuse and test.
Prime Number Program Using a Boolean Flag
A boolean flag is another common beginner approach.
n = 37
prime = True
if n < 2:
prime = False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
prime = False
break
if prime:
print("Prime")
else:
print("Not Prime")
The variable:
prime = True
initially assumes the number is prime.
If a divisor is found, it changes to:
prime = False
The program then prints the appropriate result.
Which Prime Number Method Should You Use?
The best approach depends on the problem.
| Method | Time Complexity | Space | Best Use |
|---|---|---|---|
| Basic loop | O(n) | O(1) | Learning the concept |
| √n check | O(√n) | O(1) | Checking one number |
for...else |
O(√n) | O(1) | Python-specific solution |
| 6k ± 1 | O(√n) | O(1) | Optimised single-number check |
| Sieve | O(n log log n) | O(n) | Finding many primes |
| Recursion | O(√n) | O(√n) call stack | Learning recursion |
For most interviews, start with the √n approach.
Then, if the interviewer asks for optimisation, explain the 6k ± 1 approach.
If the problem asks for all primes up to a large limit, consider the Sieve of Eratosthenes.
Common Prime Number Interview Mistakes
Mistake 1: Treating 1 as prime
This is incorrect.
1 → Not prime
A prime number must have exactly two distinct positive divisors.
Mistake 2: Forgetting numbers below 2
Always handle:
if n < 2:
return False
This covers negative numbers, zero and one.
Mistake 3: Forgetting the square-root boundary
This is incorrect:
range(2, int(n ** 0.5))
It can miss perfect squares.
For example:
25 = 5 × 5
49 = 7 × 7
Use:
range(2, int(n ** 0.5) + 1)
or preferably:
range(2, math.isqrt(n) + 1)
Mistake 4: Declaring a number prime too early
Consider:
for i in range(2, n):
if n % i != 0:
print("Prime")
This is incorrect because finding one number that does not divide n does not prove that n is prime.
You need to check all possible divisors until you find one that divides evenly.
Mistake 5: Forgetting 2
Some beginners assume every even number is composite.
That is incorrect.
2 → Prime
It is the only even prime.
Mistake 6: Assuming every 6k ± 1 number is prime
This is also incorrect.
For example:
25 = 6(4) + 1
but 25 is not prime.
The 6k ± 1 rule reduces the number of candidates. It does not eliminate the need for divisibility testing.
How to Explain Prime Number Logic in an Interview
If an interviewer asks:
“How would you check whether a number is prime?”
A strong answer can be:
“First, I would handle numbers less than 2 because they are not prime. Then I would check whether the number is divisible by any integer from 2 through its square root. If I find a divisor, the number is composite. If no divisor is found, it is prime. This reduces the complexity from O(n) to O(√n).”
If they ask:
“Can you optimise it further?”
You can explain:
“Yes. After checking 2 and 3, I can test only numbers of the form 6k ± 1 because every prime greater than 3 must have that form. The asymptotic complexity remains O(√n), but the number of divisibility checks is reduced.”
If they ask:
“What if you need all primes up to one million?”
You can answer:
“I would use the Sieve of Eratosthenes because it generates all primes up to a limit efficiently in O(n log log n) time with O(n) space.”
This demonstrates both coding ability and algorithmic understanding.
Prime Numbers vs Composite Numbers
Understanding the difference is useful in interviews.
| Property | Prime | Composite |
|---|---|---|
| Greater than 1 | Yes | Yes |
| Exactly two positive divisors | Yes | No |
| Example | 2, 3, 5, 7 | 4, 6, 8, 9 |
| Smallest | 2 | 4 |
The number 1 is neither prime nor composite.
Examples
2 → Prime
3 → Prime
4 → Composite
5 → Prime
6 → Composite
7 → Prime
8 → Composite
9 → Composite
10 → Composite
11 → Prime
Time Complexity: Why It Matters in Interviews
An interviewer may not only evaluate whether your program produces the correct answer.
They may ask:
“How efficient is your solution?”
Consider these two approaches.
Basic approach
for i in range(2, n):
Time complexity:
O(n)
Square-root approach
for i in range(2, int(n ** 0.5) + 1):
Time complexity:
O(√n)
The second approach is significantly more efficient.
For example, if:
n = 1,000,000
then:
n = 1,000,000 checks approximately
√n = 1,000 checks approximately
The difference becomes increasingly important as input values grow.
Space Complexity
The standard √n prime-checking algorithm uses:
O(1) additional space.
It only stores a few variables.
The Sieve of Eratosthenes uses:
O(n) space because it maintains an array indicating whether each number is prime.
Therefore, there is a trade-off:
Single number
→ √n method
→ Low memory
Many primes
→ Sieve
→ More memory, much better overall efficiency
FAQs
Is 1 a prime number?
No.
A prime number must have exactly two distinct positive divisors. The number 1 has only one positive divisor, so it is neither prime nor composite.
What is the smallest prime number?
2 is the smallest prime number.
It is also the only even prime number.
Why is 2 the only even prime?
Every even number greater than 2 is divisible by both 1, 2 and itself, so it has more than two positive divisors.
For example:
6 → 1, 2, 3, 6
Therefore, 6 is not prime.
What is the fastest way to check whether one number is prime in Python?
For a normal single-number problem, checking divisors up to √n is an efficient and simple approach.
For further optimisation, the 6k ± 1 method reduces the number of candidates tested.
Why do we check only up to √n?
If a number has a factor greater than its square root, it must have a corresponding factor smaller than its square root.
Therefore, if no divisor exists up to √n, there cannot be another divisor above √n that forms a factor pair.
What is the time complexity of checking a prime using √n?
The time complexity is:
O(√n)
The algorithm uses constant additional space:
O(1).
What is the Sieve of Eratosthenes?
The Sieve of Eratosthenes is an algorithm used to find all prime numbers up to a given limit.
It repeatedly marks multiples of known prime numbers as composite.
Its time complexity is approximately:
O(n log log n)
with:
O(n) space.
How do I print prime numbers between 1 and 100?
You can loop from 2 to 100 and apply a prime-checking function.
for n in range(2, 101):
if is_prime(n):
print(n)
The result is:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67
71 73 79 83 89 97
Why is math.isqrt() better than n ** 0.5?
math.isqrt() returns an exact integer square root and avoids relying on floating-point calculations.
For integer-based algorithms, it is a clearer and safer choice.
Can prime checking be done without loops?
It can be implemented recursively, but recursion is generally unnecessary for this problem.
An iterative approach is usually simpler, more readable and memory-efficient.
Can Python’s built-in functions directly tell whether a number is prime?
Python does not have a standard built-in is_prime() function.
You typically implement the logic yourself or use a third-party mathematical library when appropriate.
For coding interviews, implementing the algorithm yourself is usually expected.
Final Takeaway
Prime-number programs are simple enough for beginners but useful enough to appear frequently in Python coding interviews because they test several important concepts at once. Start with the basic loop to understand the logic, then learn the √n approach because it reduces the complexity to O(√n). If the interviewer asks for further optimisation, explain the 6k ± 1 technique. When the problem requires finding many primes up to a limit, use the Sieve of Eratosthenes. Most importantly, remember the edge cases: numbers below 2 are not prime, 1 is not prime, and 2 is the only even prime. If you can explain the logic, write the code, discuss its complexity and improve the solution when asked, you have covered the key skills interviewers are looking for in a prime-number problem.