Prime or not in Python

Prime numbers play a central role in many applications like cryptography. So it is a necessity to check for prime numbers using Python programs in various applications. A prime number is a number which doesn't have any factors other than one and itself. Below we'll see programs that can find out if a given number is prime or not.

Basic Approach

We take the following approach to decide whether a number is prime or not ?

  • Check if the number is positive or not. As only positive numbers can be prime numbers.

  • We divide the number with all the numbers in the range of 2 to one number less than given number.

  • If the remainder becomes zero for any number in this range then it is not a prime number.

Example

x = 23
if x > 1:
    for n in range(2, x):
        if (x % n) == 0:
            print(x, "is not prime")
            print(n, "times", x // n, "is", x)
            break
    else:
        print(x, "is a prime number")
else:
    print(x, "is not prime number")

The output of the above code is ?

23 is a prime number

Optimized Method Using 6i±1 Form

All prime numbers greater than 3 can be represented in the form of 6i±1. This means they are either 6i+1 or 6i-1 where i is a positive integer. In the below example we optimize the prime checking by only testing divisors of this form, significantly reducing the number of iterations needed ?

Example

def check_prime(n):
    # Check for cases of 2 and 3
    if (n 

The output of the above code is ?

31 is prime: True
25 is prime: False

Simple Function Approach

Here's a more straightforward function that checks primality by testing divisors only up to the square root of the number ?

import math

def is_prime(n):
    if n 

The output of the above code is ?

2 is prime
17 is prime
25 is not prime
29 is prime
100 is not prime

Performance Comparison

Method Time Complexity Best For
Basic approach O(n) Understanding concept
Square root method O(?n) General purpose
6i±1 optimization O(?n/3) Large numbers

Conclusion

For basic understanding, use the simple division method. For better performance, use the square root approach or the 6i±1 optimization which reduces computation time significantly for larger numbers.

Updated on: 2026-03-15T17:32:06+05:30

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements