Prime Number Program in Python with Output
Check whether a number is prime, and print all prime numbers in a given range, using Python.
- Time
O(sqrt(n)) to check one number, about O(m sqrt(m)) to check every number up to m - Space
O(1) for the check, O(k) to store k primes in a list - Hints3
- Read4 min
A prime number is greater than 1 and has no divisor other than 1 and itself. In Python, return False if n < 2, then try divisors i from 2 while i * i <= n. If any n % i == 0, n is not prime. If the loop finishes, n is prime. To print primes in a range, call this check for every number in the range.
Problem statement
Write a prime number program in Python.
- Check whether a single number is prime. For example 29 is prime and 15 is not.
- Print all prime numbers in a range, for example from 1 to 50.
Explain why checking divisors only up to the square root is enough.
An integer n for the single check, or two integers low and high for the range.
True or False for one number, or the list of primes in the range.
Examples
n = 29True29 is not divisible by 2, 3, 4 or 5, and 6 x 6 = 36 is already more than 29.
n = 15False15 % 3 == 0, so 15 has a divisor other than 1 and itself.
range 1 to 502 3 5 7 11 13 17 19 23 29 31 37 41 43 47These are the 15 numbers in the range with exactly two divisors.
Constraints
- Numbers below 2 are not prime
- The square root method is fast enough for n up to about 10^12 in a quick script
Think before you code
Reveal the questions to ask yourself first
- Why are 0, 1 and negative numbers not prime?
- If 91 = 7 x 13, do you need to test 13 once you have found 7?
- Once you find one divisor, should the loop keep running?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Prime logic in simple words
A prime has exactly two divisors: 1 and itself. So try every possible divisor from 2
upwards. If one of them divides n with no remainder, n is not prime.
Why stop at the square root?
Divisors come in pairs. For 36: 2 x 18, 3 x 12, 4 x 9, 6 x 6. In every pair, one
number is at most 6, the square root of 36. So if n has any divisor, it has one that
is no bigger than sqrt(n). Checking up to there is enough.
| n | Divisors tried (naive, 2 to n-1) | Divisors tried (up to sqrt n) |
|---|---|---|
| 97 | 95 | 8 |
| 10007 | 10005 | 99 |
Check prime number in Python
- If
n < 2, returnFalse. - Set
i = 2. Whilei * i <= n: ifn % i == 0, returnFalse; elsei += 1. - Return
True.
Prime numbers in a range in Python
Loop over the range and print each number for which is_prime(n) is True.
Dry run
Walk through the example step by step
Checking n = 29:
i | i * i | i * i <= 29 | 29 % i
--+-------+-------------+-------
2 | 4 | yes | 1
3 | 9 | yes | 2
4 | 16 | yes | 1
5 | 25 | yes | 4
6 | 36 | no, stop | -
No divisor was found, so 29 is prime.
Checking n = 15: i = 2 gives remainder 1, i = 3 gives remainder 0, so the
function returns False at once.
Solution
Reveal the full Python solution
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 [2, 29, 15, 1, 97]:
print(n, "->", is_prime(n))
print("Primes from 1 to 50:")
for n in range(1, 51):
if is_prime(n):
print(n, end=" ")
print()Output:
2 -> True
29 -> True
15 -> False
1 -> False
97 -> True
Primes from 1 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
For n = 2 the loop never runs, because 2 x 2 = 4 is more than 2, so it returns
True. print(n, end=" ") keeps the primes on one line.
Prime number program in Python with for-else
Many textbooks show this version. The else belongs to the for loop and runs only
if the loop finished without break.
n = int(input("Enter a number: "))
if n < 2:
print(n, "is not a prime number")
else:
for i in range(2, n):
if n % i == 0:
print(n, "is not a prime number")
break
else:
print(n, "is a prime number")
Enter a number: 17
17 is a prime number
Enter a number: 21
21 is not a prime number
It is easy to read, but it tries every divisor up to n - 1. For large primes that is
slow. Change range(2, n) to range(2, int(n ** 0.5) + 1) to use the square root rule.
Prime numbers in a range with user input
low = int(input("Enter start: "))
high = int(input("Enter end: "))
primes = []
for n in range(max(low, 2), high + 1):
is_prime = True
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
is_prime = False
break
if is_prime:
primes.append(n)
print("Primes:", primes)
print("Count:", len(primes))
Enter start: 10
Enter end: 50
Primes: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Count: 11
max(low, 2) skips 0 and 1, and high + 1 makes the end of the range inclusive.
Integer square root with math.isqrt()
n ** 0.5 returns a float. For very large numbers, math.isqrt(n) is safer because
it returns the exact integer square root.
import math
n = 91
print(math.isqrt(n))
for i in range(2, math.isqrt(n) + 1):
if n % i == 0:
print(n, "=", i, "x", n // i)
break
9
91 = 7 x 13
The Java version with the same logic is on check whether a number is prime, and the range version is on print all prime numbers between 1 and n. For many primes at once, the Sieve of Eratosthenes is faster; see generate the first n prime numbers.
O(sqrt(n)) to check one number, about O(m sqrt(m)) to check every number up to mO(1) for the check, O(k) to store k primes in a listReview before the interview
Common mistakes
- Treating 1 as prime. A prime must be greater than 1, so handle n < 2 first.
- Writing range(2, int(n ** 0.5)) without + 1. Then 25 is reported as prime, because 5 is never tested.
- Printing "prime" inside the loop as soon as one divisor fails. You can only say prime after every divisor has been tried.
- Forgetting break in the for-else version, so the else part runs even when a divisor was found.
Edge cases to test
- 2 is the only even prime. The while loop does not run for it, so it returns True.
- 0, 1 and negative numbers return False.
- Perfect squares like 49 are caught when i reaches 7, because the condition is i * i <= n.
Interview follow-ups
- How would you print the first n prime numbers instead of primes up to n?
- How does the Sieve of Eratosthenes find all primes up to n faster?
- How would you find the prime factors of a number?
Keep practising
Check Whether a Number Is Prime
Hints · Dry run · SolutionSolve Similar problemPrint All Prime Numbers Between 1 and N
Hints · Dry run · SolutionSolve Similar problemGenerate the First N Prime Numbers
Hints · Dry run · SolutionSolve Similar problemFind All Factors of a Number
Hints · Dry run · SolutionSolve Related learningLoops In Programming
TutorialLearn Related learningWhat Is Python Used For
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
