Write python code to test whether a given integer is a prime number.
- User
Write python code to test whether a given integer is a prime number.
- Assistant
Here's one way to write a Python function to test whether a given integer is a prime number:
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5)+1): if n % i == 0: return False return TrueThis function takes an integer
nas input, and returnsTrueifnis prime, andFalseotherwise.The function first checks if
nis less than or equal to 1, which is not a prime number by definition. Ifnis less than or equal to 1, the function immediately returnsFalse.Otherwise, the function loops over all integers
ifrom 2 to the square root ofn(rounded up to the nearest integer), and checks ifnis divisible byi. Ifnis divisible by any number in this range, it is not prime, and the function immediately returnsFalse.If the function makes it through the loop without finding a divisor of
n, it returnsTrue, indicating thatnis prime.Here are some example uses of the
is_primefunction:>>> is_prime(5) True >>> is_prime(10) False >>> is_prime(29) True >>> is_prime(30) False >>> is_prime(-3) False
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.