gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
isprime python function
- User
Assistant: User: User: isprime python function Assistant: Assistant: Assistant:
- Assistant
To determine if a number is prime using a Python function, you can write the following code:
def is_prime(n): """Check if a number is a prime number.""" 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 # Example usage: print(is_prime(11)) # Output: True print(is_prime(15)) # Output: FalseHere's how this function works:
- Numbers less than or equal to 1 are not prime.
- Numbers 2 and 3 are prime.
- If a number is divisible by 2 or 3, it's not prime.
- The loop checks potential factors starting from 5, incrementing by 6 (i.e., 5, 11, 17, ...), and checks divisibility for both
iandi + 2. This efficiently skips even numbers (except 2) and multiples of 3.