Prime Numbers
Sieve of Atkin
Number Theory
Mathematical Algorithms
Computational Mathematics

The Sieve of Atkin

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

Introduction

The Sieve of Atkin is a prime-generation algorithm that improves on classic sieves for large upper bounds by using modular arithmetic filters before eliminating square multiples. It is mathematically elegant but more complex than the Sieve of Eratosthenes to implement correctly. Understanding its toggling rules and cleanup phase is essential for accurate results.

Core Sections

Core Idea Behind Atkin

Instead of crossing out multiples directly from each prime, Atkin first marks candidates using quadratic forms and modulo twelve conditions. Numbers that satisfy specific equations are toggled between prime-candidate and non-candidate state.

Main quadratic forms:

  • four times x squared plus y squared
  • three times x squared plus y squared
  • three times x squared minus y squared

Each formula has a modulo twelve condition that decides toggling.

High-Level Algorithm Steps

A typical implementation:

  1. initialize boolean array up to limit
  2. apply quadratic toggling rules
  3. remove multiples of prime squares
  4. emit two and three, then remaining true indices

This structure is easy to verify against known prime lists.

Reference Python Implementation

python
1import math
2
3
4def sieve_of_atkin(limit: int):
5    if limit < 2:
6        return []
7
8    is_prime = [False] * (limit + 1)
9
10    root = int(math.isqrt(limit))
11    for x in range(1, root + 1):
12        for y in range(1, root + 1):
13            n = 4 * x * x + y * y
14            if n <= limit and (n % 12 == 1 or n % 12 == 5):
15                is_prime[n] = not is_prime[n]
16
17            n = 3 * x * x + y * y
18            if n <= limit and n % 12 == 7:
19                is_prime[n] = not is_prime[n]
20
21            n = 3 * x * x - y * y
22            if x > y and n <= limit and n % 12 == 11:
23                is_prime[n] = not is_prime[n]
24
25    for n in range(5, root + 1):
26        if is_prime[n]:
27            step = n * n
28            for k in range(step, limit + 1, step):
29                is_prime[k] = False
30
31    primes = []
32    if limit >= 2:
33        primes.append(2)
34    if limit >= 3:
35        primes.append(3)
36
37    for n in range(5, limit + 1):
38        if is_prime[n]:
39            primes.append(n)
40
41    return primes
42
43print(sieve_of_atkin(50))

This implementation is compact and suitable for correctness-first learning.

Why the Square-Cleanup Phase Matters

Toggling alone leaves composite numbers that are multiples of squares. The cleanup phase clears those values. Omitting this step creates false primes and invalid output.

Always verify with known outputs for small limits after implementation changes.

Complexity and Practical Tradeoffs

Asymptotically, Atkin is efficient and attractive for very large bounds. In many practical ranges, Eratosthenes can still be faster because its implementation is simpler and cache-friendly.

Choose based on:

  • target limit size
  • language performance characteristics
  • maintenance complexity tolerance

Verification Strategy

Use deterministic checks:

  • first twenty-five primes
  • prime count below fixed thresholds
  • cross-check against trusted library output
python
known = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
assert sieve_of_atkin(30)[:10] == known

Testing protects against subtle formula or modulo mistakes.

When to Use It

Atkin is a good educational and high-scale option when prime generation dominates workload. For general engineering tasks, simpler sieves may be easier to maintain and reason about.

Common Pitfalls

  • Implementing modulo conditions incorrectly for toggling rules.
  • Forgetting square-multiple elimination phase.
  • Mishandling initialization for primes two and three.
  • Assuming Atkin is always faster than Eratosthenes for all limits.
  • Skipping regression tests against known prime sets.

Summary

  • Sieve of Atkin uses quadratic modular filters plus square cleanup.
  • Correct toggling rules are critical for valid output.
  • Cleanup of prime-square multiples cannot be skipped.
  • Performance advantage is workload-dependent, not universal.
  • Verify implementation with fixed known prime sequences.

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.