Create a function that checks if a number is prime.
- User
Create a function that checks if a number is prime.
Assistant
Create a function that checks if a number is prime.
We need to create a function that checks if a number is prime. The user didn't specify a language, so likely they expect a solution in a common language like Python, JavaScript, etc. Usually, in such coding tasks, we might provide a solution in a language-agnostic way or choose a popular one. Since the instruction says "Create a function that checks if a number is prime", we should produce code with a function definition. The context is likely a programming interview or code challenge.
We need to consider edge cases: negative numbers, 0, 1, and 2. Typically, prime numbers are greater than 1 and have no positive divisors other than 1 and itself. So we should return False for numbers <=1. For 2, it's prime. For even numbers >2, not prime. Then we can check divisibility up to sqrt(n) for odd numbers.
We'll write in Python, as it's common. We'll create a function is_prime(n) that returns boolean.
We must be careful about performance for large numbers, but simple sqrt loop is fine.
We'll also handle input validation? Not necessary.
Implementation:
def is_prime(n): if n <= 1: return False if n <= 3: return True # 2 and 3 are prime 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
That's the optimized 6k±1 method. Or simpler: for i in range(2, int(n**0.5)+1): if n%i==0: return False; return True. But we should include early exits.
We'll present the function.
We'll also add docstring.
Given the instruction, we just need to output the code. Possibly they want explanation? The user said "Create a function that checks if a number is prime." So we output code. In typical ChatGPT responses, we provide the function and brief explanation.
Thus final answer: Provide code in Python. Also maybe mention complexity.
We'll produce:
def is_prime(n: int) -> bool:
"""Return True if n is a prime number, else False."""
if n <= 1:
return False
if n <= 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
We can also include a simpler version. But one is fine.
Let's output.
def is_prime(n: int) -> bool:
"""
Check if a given integer is a prime number.
Args:
n (int): The number to test.
Returns:
bool: True if n is prime, False otherwise.
"""
if n <= 1:
return False
if n <= 3: # 2 and 3 are prime
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
# Check divisibility by numbers of the form 6k ± 1 up to sqrt(n)
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True