Prime Numbers
Number Theory
Algorithms
Mathematics
Sieve of Eratosthenes

Generate a list of primes up to a certain number

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Generating a list of prime numbers up to a certain number is a common problem in computer science and mathematics. Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Understanding methods to generate such a list efficiently is important for various applications in cryptography, numerical methods, and algorithm design. This article delves into techniques to generate primes, focusing on efficient algorithms, technical explanations, and examples.

Overview of Prime Number Generation

Prime number generation involves finding all prime numbers up to a given limit N . A naive approach would involve checking divisibility for each number up to N , but this quickly becomes inefficient as N grows. Instead, we use more efficient algorithms to reduce computational complexity.

Key Concepts

Prime Numbers: An integer greater than 1 without divisors other than 1 and itself. • Efficiency: Algorithms should reduce the numbers of checks needed for primality. • Complexity: Time complexity determines how an algorithm's execution time grows as the size of the input increases.

Simple Approaches

Trial Division

The simplest algorithm to check if a number n is prime is Trial Division. This involves testing if n is divisible by any number less than n . To check if a number n is prime, perform the following steps:

  1. Check divisibility by all integers from 2 to n\sqrt{n}.
  2. If none divides n , it is a prime.

Complexity: This method has a time complexity of O(nn)O(n \sqrt{n}), making it inefficient for large N .

Example: To check if 29 is prime, test divisibility by 2, 3, 4, and 5 (since 295.38\sqrt{29} \approx 5.38).

Sieve of Eratosthenes

The Sieve of Eratosthenes is an ancient and more efficient algorithm to generate all primes up to N . It operates as follows:

  1. Create a boolean array of size N+1 , initialized to True (indicating potential primality).
  2. Set array positions 0 and 1 to False as 0 and 1 are not primes.
  3. Starting from the first prime (2), iterate and mark multiples of each prime as False .
  4. Move to the next number in the array and repeat until reaching N\sqrt{N}.

Complexity: The time complexity of this algorithm is O(Nlog(log(N)))O(N \log(\log(N))), which is much better for large numbers than trial division.

Example: Generate primes up to 10.

• Initialize: [True, True, True, True, True, True, True, True, True, True, True]

• After marking multiples of 2: [True, True, True, True, False, True, False, True, False, True, False]

• After marking multiples of 3: [True, True, True, True, False, True, False, True, False, False, False]

• Result: 2, 3, 5, 7 are prime.

Advanced Techniques

Sieve of Atkin

The Sieve of Atkin is a modern algorithm that is optimized for large inputs with complexity O(N/log(log(N)))O(N/\log(\log(N))). It is more complicated but can be slightly faster than the Sieve of Eratosthenes for very large values of N . It works by using a series of mathematical wheels to determine potential primes and perform modulo calculations to rule out non-primes.

Segmented Sieve

For even larger ranges, the Segmented Sieve can be used, which allows the memory-efficient generation of primes by processing in small segments or blocks. This can be advantageous when N is too large to handle in a single pass due to memory constraints.

Summary Table

AlgorithmComplexityProsCons
Trial DivisionO(nn)O(n \sqrt{n})SimpleInefficient for large N
------------
Sieve of EratosthenesO(Nlog(log(N)))O(N \log(\log(N)))Efficient for medium N
High memory usage
Sieve of AtkinO(N/log(log(N)))O(N/\log(\log(N)))More efficient for large N
Complex implementation
Segmented SieveO(Nlog(log(N)))O(N \log(\log(N)))Handles massive rangesComplexity in design

Additional Considerations

Memory Usage

• Consider the memory footprint of each algorithm, especially for high N values. • The Sieve of Eratosthenes can require significant memory for the boolean array.

Parallel Processing

• Many sieve algorithms can be modified to run in parallel, improving efficiency on modern multi-core processors.

Applications

Cryptography: Prime numbers are fundamental in public-key cryptography algorithms like RSA. • Random Number Generation: Primes are useful in generating pseudo-random numbers. • Mathematical Research: The distribution of prime numbers is an area of ongoing research in number theory.

Generating a list of primes efficiently requires careful consideration of algorithm complexity, memory usage, and the size of N . Whether through classical methods like the Sieve of Eratosthenes or more advanced techniques such as the Sieve of Atkin, understanding these algorithms provides a foundation for tackling diverse applications in computing and mathematics.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.