The user wants me to write a Python function to check if a number is prime.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Let me write a function that:
Handles edge cases (numbers less than 2 are not prime)
Checks if the number is divisible by any number from 2 to sqrt(n)
I'll provide a few different approaches:
Basic approach - checking divisibility up to sqrt(n)
Optimized approach - checking 2 separately, then only odd numbers
Even more optimized - checking 2, 3, then numbers of form 6k±1
Let me write this out:
python
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
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
I'll also show examples and explain the logic. # Python Function to Check Prime Numbers
Basic Solution
python
def is_prime(n):
"""
Check if a number is prime.
Args:
n: Integer to check
Returns:
True if n is prime, False otherwise
"""
# Numbers less than 2 are not prime
if n < 2:
return False
# Check for divisibility from 2 to sqrt(n)
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
Optimized Solution
python
def is_prime_optimized(n):
"""
Optimized prime check - skips even numbers after checking 2.
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Only check odd numbers up to sqrt(n)
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
Most Optimized Solution (6k ± 1 method)
python
def is_prime_fast(n):
"""
Fastest method - uses the fact that all primes > 3
are of the form 6k ± 1
"""
if n < 2:
return False
if n in (2, 3):
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
Usage Examples
python
# Test the functions
test_numbers = [1, 2, 3, 4, 17, 18, 97, 100]
print("Number | Is Prime?")
print("-" * 20)
for num in test_numbers:
print(f"{num:6} | {is_prime(num)}")
For n = 29:
Step 1: Is 29 < 2? → No
Step 2: Is 29 == 2? → No
Step 3: Is 29 even? → No
Step 4: Check odd divisors from 3 to √29 (≈5.4)
- 29 % 3 = 2 ≠ 0 ✓
- 29 % 5 = 4 ≠ 0 ✓
Step 5: No divisors found → 29 IS PRIME ✓
Key Points
Aspect
Explanation
Why √n?
If n = a × b, one factor must be ≤ √n
Skip evens
All even numbers > 2 are not prime
6k±1 trick
All primes > 3 are adjacent to multiples of 6
Time Complexity
O(√n) for all versions
Bonus: Find All Primes in Range
python
def primes_in_range(start, end):
"""Return list of all primes in range [start, end]"""
return [n for n in range(start, end + 1) if is_prime(n)]
# Example: Find primes between 1 and 50
print(primes_in_range(1, 50))
# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
The optimized solution is recommended for most use cases - it's simple, efficient, and easy to understand!