To solve this problem, we need to determine if a given number is a prime number. A prime number is defined as a number greater than 1 that has no divrs other than 1 and itself.
Approach
The approach to check for a prime number involves the following steps:
- Edge Cases: If the number is less than or equal to 1, it is not a prime number.
- Even Number Check: If the number is 2, it is the only even prime number. Any other even number is not prime.
- Odd Divrs Check: For odd numbers greater than 2, check divisibility by all odd numbers starting from 3 up to the square root of the number. This is because if a number has a factor larger than its square root, the corresponding factor would be smaller than the square root, so we don't need to check beyond that.
Solution Code
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
Explanation
- Edge Case Handling: The function first checks if the number is less than or equal to 1, returning
Falseimmediately since these are not primes. - Even Prime Check: The number 2 is the only even prime, so we return
Truefor 2. - Even Number Exclusion: Any even number greater than 2 is not prime, so we return
Falsefor such numbers. - Odd Divrs Check: For odd numbers, we start checking from 3 and increment by 2 (to skip even numbers) until the square of the current divr exceeds the number. If any divr divides the number evenly, it is not prime. If no such divr is found, the number is prime.
This approach efficiently checks for primes by reducing the number of divrs to check, making it optimal for most practical purposes. The time complexity is O(√n), which is efficient for large numbers.
Example Usage:
is_prime(2)→Trueis_prime(9)→Falseis_prime(17)→Trueis_prime(0)→Falseis_prime(-5)→False
This function correctly identifies prime numbers and handles all edge cases appropriately.


作者声明:本文包含人工智能生成内容。