Example output
Certainly! Here's a Python code snippet to check if a number is prime or not, with a focus on efficiency, readability, and edge-case handling:
```python
def is_prime(n):
"""
Check if a number is prime.
Parameters:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwise.
"""
# Edge case handling
if not isinstance(n, int):
raise ValueError("Input must be an integer.")
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
# Check for factors from 5 to sqrt(n)
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Example usage:
if __name__ == "__main__":
test_numbers = [2, 3, 4, 5, 16, 17, 18, 19, -5, 1.5]
for num in test_numbers:
try:
result = is_prime(num)
print(f"{num} is prime: {result}")
except ValueError as e:
print(f"Error checking {num}: {e}")
```
### Explanation:
1. **Edge Case Handling**:
- **Non-integer Input**: Checks if the input is an integer. If not, raises a `ValueError`.
- **Negative Numbers and Zero**: Numbers less than or equal to 1 are not prime by definition.
2. **Initial Checks**:
- **Immediate Return for Small Values**: Handles numbers 2 and 3 directly (both are prime). It also eliminates even numbers and multiples of 3 quickly.
3. **Efficient Prime Checking**:
- **Only Check Up to sqrt(n)**: We only need to check up to the square root of `n` for factors. This reduces the number of checks significantly.
- **6k ± 1 Optimization**: After checking for divisibility by 2 and 3, we can use a step of 6 to check potential factors. This skips over numbers that are obviously not prime (i.e., multiples of 2 and 3).
### Example Usage:
To test the code, simply run the script. It will print whether each number in `test_numbers` is prime or not, and handle errors for non-integer inputs gracefully. Adjust `test_numbers` as needed to test different values.