To check if a number is prime in Python, we can use the following algorithm:
Here's a Python function that implements this algorithm:
main.py179 chars10 linesThe function takes an integer n as input and returns True if n is prime, and False otherwise. We start by checking if n is less than 2, since 0 and 1 are not prime. Then we loop over all the integers from 2 to the square root of n (rounded up), checking if n is divisible by each one. If we find a divisor, we return False since the number is not prime. If we have looped over all the possible divisors without finding one, we know that the number is prime and we return True.
We can test the function like this:
main.py203 chars11 lines
gistlibby LogSnag