Python Program to Check if Number is Prime
def is_prime(n): return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1)).Examples
How to Think About It
Algorithm
Code
def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True print(is_prime(2)) print(is_prime(15)) print(is_prime(17))
Dry Run
Let's trace the number 15 through the code to see if it is prime.
Check if number is <= 1
15 is greater than 1, so continue.
Loop from 2 to sqrt(15)
Check divisors 2, 3 (since sqrt(15) ≈ 3.87).
Check divisibility by 2
15 % 2 != 0, so continue.
Check divisibility by 3
15 % 3 == 0, divisor found, return False.
| Divisor | 15 % Divisor | Is Divisible? |
|---|---|---|
| 2 | 1 | No |
| 3 | 0 | Yes |
Why This Works
Step 1: Check number validity
A prime number must be greater than 1, so we return False immediately if not.
Step 2: Limit divisor checks
We only check divisors up to the square root because any larger factor would have a smaller complementary factor already checked.
Step 3: Return result
If no divisor divides the number evenly, the number is prime, so return True.
Alternative Approaches
def is_prime(n): return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1)) print(is_prime(29))
def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True print(is_prime(37))
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of n, so the time grows roughly with √n.
Space Complexity
The program uses a fixed amount of extra space regardless of input size.
Which Approach is Fastest?
Checking only odd divisors after 2 is faster than checking all numbers; using all() with a generator is concise but similar in speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop up to sqrt(n) | O(√n) | O(1) | Clarity and beginners |
| all() with generator | O(√n) | O(1) | Concise Pythonic code |
| Check 2 then odds only | O(√n/2) | O(1) | Efficiency for larger numbers |