Back to Data Structures & Algorithms
2025-12-216 min read

Algorithm 5: Check whether a number is prime or not (Data Structures & Algorithms)

Learn Algorithm 5: Check whether a number is prime or not (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

Prime numbers play a significant role in various mathematical and computational applications, such as cryptography, number theory, and algorithm analysis. Understanding how to write efficient algorithms for checking prime numbers can help you solve complex problems and improve your coding skills. Additionally, learning about prime numbers can provide valuable insights into the properties of integers and their relationships.

Prime numbers are crucial in modern cryptography, where they are used to create secure communication channels, digital signatures, and public-key encryption systems like RSA (Rivest–Shamir–Adleman). The security of these systems relies on the difficulty of factoring large composite numbers into their prime factors. Finding the prime factors of a large number is computationally expensive, making it difficult for attackers to break the encryption.

Prerequisites

Before diving into the core concept of this lesson, you should have a basic understanding of:

  1. Python programming language syntax and control structures (if-else statements, loops)
  2. Basic data types in Python (integers, floats, strings)
  3. Understanding what a prime number is and its properties
  4. Familiarity with mathematical operations and concepts like modulo arithmetic, factors, multiples, and the Fundamental Theorem of Arithmetic
  5. Knowledge of Big O notation to analyze the time complexity of algorithms

Core Concept

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number can only be divided evenly by 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, and so on.

Properties of Prime Numbers

  1. A prime number cannot be factored into smaller integers that multiply to equal the prime number.
  2. Every positive integer greater than 1 either is a prime number or can be expressed as a product of primes (Fundamental Theorem of Arithmetic).
  3. The only even prime number is 2, and all other even numbers are not prime.
  4. There are infinitely many prime numbers.
  5. Prime numbers follow the Prime Number Theorem, which states that the number of prime numbers less than or equal to x is approximately x / ln(x).

Here's a simple algorithm to check if a given number is prime or not:

  1. If the number is less than or equal to 1, it is not prime (since 1 has no divisors other than itself).
  2. If the number is even (i.e., its last digit is 0, 2, 4, 6, or 8), it is not prime (except for 2, which is the only even prime number).
  3. Starting from 3, check if the given number can be divided evenly by any number up to its square root. If it can, then the number is not prime; otherwise, it is prime.
  4. For larger input numbers, consider using more efficient algorithms like the Sieve of Eratosthenes or Miller-Rabin primality test for better performance.

Time Complexity Analysis

The time complexity of our simple algorithm is O(sqrt(n)), as we need to check divisibility up to the square root of the input number n. This may not be efficient enough for large input numbers, so it's important to consider more advanced algorithms like the Sieve of Eratosthenes or Miller-Rabin primality test for better performance.

Here's a Python function that implements this algorithm:

def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1):
if n % i == 0:
return False
return True

In this function, we first check if the input number n is less than or equal to 1, and if so, return False. Then, we check if n is 2 (since it's the only even prime number). If n is even but not 2, we return False. After that, we loop through numbers from 3 up to the square root of n and check if n can be divided evenly by any of them. If such a divisor is found, we return False, indicating that the input number is not prime; otherwise, we return True.

Worked Example

Let's test our function with some examples:

print(is_prime(2)) # True (2 is a prime number)
print(is_prime(4)) # False (4 is not a prime number)
print(is_prime(7)) # True (7 is a prime number)
print(is_prime(15)) # False (15 is not a prime number)

Common Mistakes

Forgetting to handle the edge case of n <= 1

If you forget to check if the input number is less than or equal to 1, your function will incorrectly classify these numbers as prime.

Not checking for even numbers (except 2)

If you don't exclude even numbers other than 2 from the check, your function will incorrectly classify them as not prime.

Checking divisibility up to n instead of sqrt(n)

If you check divisibility up to n instead of its square root, your function may take longer to run for larger input numbers and may still return incorrect results if the prime number has a large factor close to its square root.

Not considering optimizations for larger inputs

For larger input numbers, more efficient algorithms like the Sieve of Eratosthenes or Miller-Rabin primality test can be used to check if a number is prime.

Neglecting time complexity analysis

Neglecting the time complexity analysis of your algorithm can lead to inefficient solutions for large input numbers. Always consider optimizing your algorithms for better performance, especially when dealing with large data sets or complex computations.

Practice Questions

  1. Write a Python function that uses the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit (e.g., 100).
  2. Implement the Miller-Rabin primality test in Python and use it to check if 31 is likely prime or composite.
  3. Analyze the time complexity of the Sieve of Eratosthenes algorithm and compare it with our simple prime checking algorithm.
  4. Write a Python function that generates the first n prime numbers using either the simple algorithm or an optimized method like the Sieve of Eratosthenes.
  5. Explain how the Prime Number Theorem can be used to estimate the number of prime numbers less than a given value.

FAQ

  1. What is a prime number? A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, it can only be divided evenly by 1 and itself.
  1. Why are prime numbers important in cryptography? Prime numbers play a crucial role in modern cryptography because they are difficult to factor, making it challenging for attackers to break encryption systems like RSA.
  1. What is the Sieve of Eratosthenes algorithm? The Sieve of Eratosthenes is an ancient algorithm used to find all prime numbers up to a given limit. It works by iteratively marking and eliminating multiples of each prime number found so far, leaving only the primes.
  1. What is the Miller-Rabin primality test? The Miller-Rabin primality test is a probabilistic algorithm used to determine whether a given number is likely prime or composite. It provides a more efficient solution for checking large numbers than the simple algorithm presented in this lesson.
  1. What is Big O notation, and why is it important? Big O notation is a mathematical notation that describes the time complexity of an algorithm as a function of the size of its input. Understanding Big O notation helps you analyze the efficiency of algorithms and choose the most appropriate one for your problem.
Algorithm 5: Check whether a number is prime or not (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn