Hey everyone! ๐
Today, we're solving a classic mathematical problem: Checking if a Number is Prime.
The Problem
The goal is to write a function that determines whether a given number is prime.
- A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
- The function should return
Trueif the number is prime, andFalseotherwise.
Examples:
-
is_prime(7)โ Should returnTrue(7 is only divisible by 1 and 7) -
is_prime(10)โ Should returnFalse(10 is divisible by 1, 2, 5, and 10) -
is_prime(2)โ Should returnTrue(2 is the only even prime number)
The Solution
Here is the Python implementation:
def is_prime(n):
"""
Checks if a number is prime.
"""
# Numbers โค 1 are not prime by definition
if n <= 1:
return False
# 2 is the only even prime number
if n == 2:
return True
# Check if n is even (and not 2)
if n % 2 == 0:
return False
# Check odd divisors from 3 up to the square root of n
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# Test cases
print(is_prime(7)) # True
print(is_prime(10)) # False
print(is_prime(2)) # True
Code Breakdown
Let's walk through the code line by line:
-
def is_prime(n):- Defines a function named
is_primethat takes an integernas input.
- Defines a function named
-
if n <= 1:- Checks if the number is less than or equal to 1.
- By mathematical definition, numbers โค 1 are not considered prime, so we return
False.
-
if n == 2:- Special case: 2 is the only even prime number.
- If
nis 2, we immediately returnTrue.
-
if n % 2 == 0:- Checks if
nis even (divisible by 2). - Since we've already handled the case where
n == 2, any other even number is not prime. - Returns
Falsefor all even numbers greater than 2.
- Checks if
-
`for i in range(3, int(n0.5) + 1, 2):`**
- This is the optimization key! We only need to check divisors up to the square root of n.
- Why? If
nhas a divisor greater than โn, it must also have a corresponding divisor smaller than โn. -
n**0.5calculates the square root ofn. -
int(...)converts it to an integer. -
+ 1ensures we include the square root itself in the range (sincerangeis exclusive of the end value). -
2as the step means we only check odd numbers (3, 5, 7, 9, ...), skipping all even numbers since we already know they're not prime.
-
if n % i == 0:- Checks if
nis divisible by the current value ofi. - If it is,
nhas a divisor other than 1 and itself, so it's not prime. - Returns
Falseimmediately.
- Checks if
-
return True- If we've checked all possible divisors and found none, the number is prime.
- Returns
True.
Example Walkthrough
Let's trace the function with is_prime(29):
- Check:
29 <= 1? No, continue. - Check:
29 == 2? No, continue. - Check:
29 % 2 == 0? No (29 is odd), continue. - Loop: Check divisors from 3 to โ29 โ 5.38, so we check 3 and 5.
-
i = 3:29 % 3 == 0? No (29 รท 3 = 9 remainder 2) -
i = 5:29 % 5 == 0? No (29 รท 5 = 5 remainder 4)
-
- Result: No divisors found, return
True. โ
Now let's trace is_prime(15):
- Check:
15 <= 1? No, continue. - Check:
15 == 2? No, continue. - Check:
15 % 2 == 0? No (15 is odd), continue. - Loop: Check divisors from 3 to โ15 โ 3.87, so we check 3.
-
i = 3:15 % 3 == 0? Yes! (15 รท 3 = 5)
-
- Result: Divisor found, return
False. โ
Key Optimizations
This implementation uses several clever optimizations:
- Early Returns: We return
Falseas soon as we find any divisor, avoiding unnecessary checks. - Reduced Search Space: Only checking up to โn dramatically reduces the number of iterations.
- Skip Even Numbers: After handling 2, we skip all other even numbers by stepping by 2 in our loop.
These optimizations make the function efficient even for larger numbers! ๐
Happy coding! ๐ป
Top comments (0)