formula for prime numbers in python

Here's a simple Python function that checks whether a given number is prime or not using the trial division method:

main.py
def is_prime(n):
    if n <= 1:
        return False
    elif n == 2:
        return True
    elif n % 2 == 0:
        return False
    else:
        for i in range(3, int(n**0.5)+1, 2):
            if n % i == 0:
                return False
        return True
263 chars
13 lines

This function first checks whether the given number is less than or equal to 1 (which is not a prime number). Then, it checks the special case of 2, which is the only even prime number. If the number is even and not equal to 2, it must be composite. Then, it uses a trial division method to check whether the given number is divisible by any odd number from 3 up to the square root of the number. If it's not divisible by any of them, it must be a prime number.

gistlibby LogSnag