Sub topic 11
Saving Memory: Odd-Only and Bit-Packed Sieves
This chapter assumes you have read the earlier chapters on the basic sieve of Eratosthenes, on starting each pass at p squared, and on the sieve's O(n) memory cost. You should be comfortable with Python lists, integer division (//), and bitwise operators (&, |, >>, <<).
The plain sieve keeps one flag for every integer from 0 to n. Speed is usually fine. Memory is what runs out first. For n = 10⁹, a Python list of booleans needs about 8 GB just for pointers, since each list slot is an 8-byte reference. This chapter covers two independent ways to shrink that:
- Odd-only sieving. You skip storage for even numbers, which halves memory.
- Bit packing. You store each flag in one bit instead of one byte or one pointer, which cuts memory by a further factor of 8.
The two combine, and both keep the same O(n log log n) running time.
Where the Memory Goes
The table below shows the storage needed for the flag array alone at n = 10⁹.
| Representation | Bytes per number tracked | Memory for n = 10⁹ |
|---|---|---|
| Python `list` of `bool` | 8 (pointer) | ~8 GB |
| `bytearray`, one byte per number | 1 | ~1 GB |
| `bytearray`, odd numbers only | 0.5 | ~500 MB |
| Bits, odd numbers only | 1/16 | ~62.5 MB |
| Bits, wheel mod 30 (8 of every 30 numbers) | 1/30 | ~33 MB |
The first step down is free in Python. Switching from list to bytearray changes no logic and saves a factor of 8. The other steps change how numbers map to positions in the array, and that mapping is where bugs show up.
Odd-Only Sieving
The Index Mapping
Every even number above 2 is composite, so storing flags for even numbers wastes half the array. Instead, let index i stand for the odd number 2i + 1:
| Index i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Value 2i + 1 | 1 | 3 | 5 | 7 | 9 | 11 | 13 | 15 |
The inverse mapping for an odd value v is i = (v - 1) // 2. Because v is odd, this equals v // 2. The largest index you need is (n - 1) // 2, so the array has (n - 1) // 2 + 1 slots. You handle 2 as a special case and add it to the output by hand. Index 0 stands for 1, which is not prime, so you clear it.
The Step Size Changes
In the plain sieve, prime p crosses out p², p² + p, p² + 2p, and so on. Half of those values are even, and even numbers are no longer stored. The odd multiples of an odd p are p², p² + 2p, p² + 4p, and so on, spaced 2p apart in value.
Moving 2p in value means moving p in index, because index = (value − 1) / 2. So the inner loop starts at index (p*p) // 2 and steps by p.
Implementation
This version uses a bytearray and slice assignment, which runs the inner loop in C and is much faster in Python than an explicit for loop.
def odd_sieve(n):
"""Return all primes <= n, storing flags only for odd numbers."""
if n < 2:
return []
size = (n - 1) // 2 + 1 # index i represents 2*i + 1
flags = bytearray([1]) * size
flags[0] = 0 # index 0 is the number 1
i = 1
while (2 * i + 1) * (2 * i + 1) <= n:
if flags[i]:
p = 2 * i + 1
start = (p * p) // 2 # index of p*p
flags[start::p] = bytes(len(range(start, size, p)))
i += 1
return [2] + [2 * k + 1 for k in range(1, size) if flags[k]]
print(odd_sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
print(len(odd_sieve(1_000_000))) # 78498The expression bytes(len(range(start, size, p))) builds a zero-filled block exactly as long as the slice. Slice assignment to a bytearray requires the lengths to match when the slice has a step. len(range(...)) computes that length without building a list.
What It Costs and What It Saves
Odd-only sieving halves memory. It also removes the pass for p = 2, which is the most expensive pass in the plain sieve because it touches n/2 entries. The total work drops by roughly a third, and the asymptotic bound stays O(n log log n). The price is the index arithmetic, plus the special case for 2 in both input handling and output.
Bit Packing
One Flag per Bit
A bytearray spends 8 bits on each true/false flag. Bit packing stores 8 flags in each byte. Flag j lives in byte j >> 3 (that is, j // 8), at bit position j & 7 (that is, j % 8).
- To test flag j:
(bits[j >> 3] >> (j & 7)) & 1 - To clear flag j:
bits[j >> 3] &= ~(1 << (j & 7))
In Python, ~(1 << k) is a negative integer. ANDing it with a byte value from 0 to 255 still gives a result from 0 to 255, so the assignment back into the bytearray is safe.
Implementation Combined with Odd-Only
def bit_sieve(n):
"""Odd-only sieve with one bit per odd number."""
if n < 2:
return []
size = (n - 1) // 2 + 1 # flag j represents 2*j + 1
bits = bytearray(b"\xff") * ((size + 7) // 8)
def is_set(j):
return (bits[j >> 3] >> (j & 7)) & 1
def clear(j):
bits[j >> 3] &= ~(1 << (j & 7))
clear(0) # the number 1
i = 1
while (2 * i + 1) * (2 * i + 1) <= n:
if is_set(i):
p = 2 * i + 1
for j in range((p * p) // 2, size, p):
clear(j)
i += 1
return [2] + [2 * j + 1 for j in range(1, size) if is_set(j)]
print(bit_sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
print(len(bit_sieve(1_000_000))) # 78498The last byte may contain padding bits beyond size. They start as 1, but the output loop stops at size, so they are never read. If you count primes by counting set bits across the whole array (for example, with int.bit_count), clear the padding first or you will overcount.
The Speed Trade-Off
Bit packing has two effects on speed that pull in opposite directions:
- Slower per operation. Every test or clear needs a shift, a mask, and a read-modify-write instead of a single store. In pure Python,
bit_sieveruns several times slower thanodd_sieve, because eachclearis an interpreted function call. - Faster memory access. A smaller array fits in CPU cache. For n = 10⁸, the odd-only bit array is about 6 MB, while a byte-per-number array is 100 MB. In C, C++, or Rust, cache misses dominate sieve time at large n, so the bit-packed version often wins despite doing more arithmetic.
In Python, then, the practical choice is usually the bytearray odd-only sieve. Bit packing is worth it in Python only when memory is the hard limit. In compiled languages, bit packing is a common default (C++'s std::vector<bool> and Rust's bitset crates do it for you).
Going Further: Wheels
Odd-only sieving is the simplest case of wheel factorization. A wheel is a pattern of residues that skips multiples of the first few primes. Skipping multiples of 2 keeps 1 of every 2 numbers. Skipping multiples of 2 and 3 keeps 2 of every 6 numbers (those ≡ 1 or 5 mod 6). Skipping 2, 3, and 5 keeps 8 of every 30 numbers. That last case is popular because 8 residues fit exactly in one byte, giving 1/30 byte per number.
Each larger wheel saves less than the one before it. The 2-wheel saves 50%, the 6-wheel saves a further 33% of what remains, and the 30-wheel saves a further 20%. Index arithmetic also gets harder, since the gaps between kept residues are no longer constant. Most hand-written sieves stop at odd-only or the 30-wheel.
When Memory Tricks Are Not Enough
All these techniques shrink the constant factor, but memory is still O(n). At n = 10¹², even the 30-wheel needs about 33 GB. Also, if you only want primes in a narrow range near 10¹², storing flags from 0 upward is wasteful. The next chapter's segmented sieve fixes this by sieving one window at a time, using only the base primes up to √hi. Odd-only and bit-packed storage apply inside each segment as well, so these techniques combine with segmentation.
Decision Guide
| Situation | Recommended representation |
|---|---|
| n up to ~10⁷ in Python | `bytearray`, optionally odd-only |
| n up to ~10⁹ in Python, memory tight | Odd-only `bytearray`, or bit-packed if under 500 MB is required |
| Compiled language, large n | Odd-only or 30-wheel bit array |
| Primes in a range far from 0 | Segmented sieve (next chapter) |
Exercise
In the odd-only sieve, at what index does the pass for p = 7 begin, what is its index step, and which value does the third index it visits represent?
Show answer
It starts at index (7 7) // 2 = 24, which represents 49. The index step is p = 7. The visited indices are 24, 31, 38, ..., so the third one is 38, which represents 2 38 + 1 = 77 = 7 * 11.
Exercise
A colleague's odd-only sieve uses flags[start::2*p] in the inner loop. Which number below 50 is the smallest composite it wrongly reports as prime, and why?
Show answer
15. For p = 3, the pass starts at index 4 (value 9) and steps 6 in index space, which is 12 in value, so it visits 9, 21, 33, 45 and skips 15, 27, 39. The pass for p = 5 starts at 25, so 15 is never crossed out. (27 and 39 also survive.)
Exercise
Estimate the memory needed by an odd-only bit-packed sieve for n = 4 * 10^9, and say whether it fits in a 256 MB limit.
Show answer
The sieve needs about n / 2 = 2 10^9 flags, at 8 flags per byte, which is 2.5 10^8 bytes, or about 250 MB (roughly 238 MiB). It fits barely under a 256 MB limit, with almost no room for the output list. Counting primes instead of storing them, or using a segmented sieve, would be safer.
Exercise
You count primes in bit_sieve by summing bin(b).count("1") over every byte in bits, then adding 1 for the prime 2. For n = 20 the result is too large. Explain the error and fix it.
Show answer
For n = 20, size = 10, so the array has 2 bytes, or 16 bits, and the 6 padding bits (flags 10 to 15) are still set. Clear them before counting, for example with for j in range(size, len(bits) * 8): clear(j). Alternatively, count only sum(is_set(j) for j in range(size)). The correct count for n = 20 is 8.