check if 3612 is a prime number in python

Here's a Python code to check if a number is prime or not:

main.py
import math

def is_prime(n):
    if n <= 1:
        return False
    elif n <= 3:
        return True
    elif n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i*i <= n:
        if n % i == 0 or n % (i+2) == 0:
            return False
        i += 6
    return True

n = 3612
if is_prime(n):
    print(n, "is a prime number")
else:
    print(n, "is not a prime number")
390 chars
22 lines

The code first checks if the number is less than or equal to 1, because any number less than or equal to 1 is not a prime. Then, it checks if the number is 2 or 3, in which case the number is a prime. If the number % 2 == 0 or number % 3 == 0, then the number is not a prime. After this, we check if the number is divisible by any number from 5 to sqrt(n) with a step of 6. We can skip checking multiples of 2 and 3 because we've already done that. If the number is not divisible by any odd number between 5 and sqrt(n), then it is a prime number.

related categories

gistlibby LogSnag