Here's a simple function to check if a number is prime in Python:
main.py173 chars10 lines
The function takes an integer n
as input, and returns True
if it is prime, and False
otherwise.
The function first checks if n
is less than 2, because 2 is the smallest prime number. If n
is less than 2, the function returns False
.
Next, the function starts a loop from 2 to the square root of n
(rounded up to the nearest integer using math.sqrt()
and int()
functions). If n
is divisible by any number in this range, it is not a prime and the function returns False
.
If the loop completes without finding any factors, n
is a prime and the function returns True
.
gistlibby LogSnag