def is_prime(n):
# 1. Prime numbers are greater than 1
if n < 2:
return False
# 2. Loop from 2 up to √n (square root of n)
# If a number has a divisor larger than its square root,
# the matching smaller divisor would already be found.
for i in range(2, int(n**0.5) + 1):
# 3. If n is divisible by i, then it's not a prime
if n % i == 0:
return False
# 4. If no divisors were found, n is prime
return True
# Test the function
print(is_prime(17)) # True → 17 is a prime number
print(is_prime(18)) # False → 18 is divisible by 2, 3, 6, 9
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Answer:
Explanation:
sqrt(n)for efficiency.