gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
write a sample python code to check number is prime or no
- User
write a sample python code to check number is prime or no
- Assistant
Certainly! Below is a sample Python code to check if a number is prime:
def is_prime(number): """Check if a number is a prime number.""" if number <= 1: return False if number <= 3: return True if number % 2 == 0 or number % 3 == 0: return False i = 5 while i * i <= number: if number % i == 0 or number % (i + 2) == 0: return False i += 6 return True # Example usage: num = 29 # Change this number to check other numbers if is_prime(num): print(f"{num} is a prime number.") else: print(f"{num} is not a prime number.")This code defines a function
is_primethat returnsTrueif the given number is prime andFalseotherwise. It includes a few optimizations, such as only checking divisibility up to the square root of the number and skipping even numbers (after checking for 2) and multiples of 3. The example usage checks if 29 is a prime number. You can change thenumvariable to test other numbers.