Sub topic 11
Saving Memory: Odd-Only and Bit-Packed Sieves
This chapter assumes you already know the basic sieve of Eratosthenes, why marking starts at p squared, and that the sieve uses O(n) memory. You should also be comfortable with Python lists, slicing, and bitwise operators such as &, |, <<, and >>.
The basic sieve is fast, but memory usually runs out before time does. A Python list of True/False stores an 8-byte pointer per entry on a 64-bit machine, so sieving to one billion would need about 8 GB. Two changes reduce that cost by more than 100 times.
Step 1: Use One Byte per Flag
A bytearray stores each flag in one byte instead of one pointer. That alone cuts memory by 8 times. It also supports slice assignment, which crosses out a whole run of multiples in fast C code instead of a Python loop.
Step 2: Store Only Odd Numbers
Every even number above 2 is composite, so storing flags for them wastes half the array. In an odd-only sieve, index i stands for the number 2*i + 1.
Two facts make the index arithmetic work:
- The odd number
vsits at indexv // 2. For example, 9 is at index 4. - Odd multiples of
p(p², p² + 2p, p² + 4p, ...) differ by2pin value. That is a step of exactlypin index.
def odd_sieve(n):
if n < 2:
return []
size = (n + 1) // 2 # odd numbers 1, 3, ..., up to n
flags = bytearray([1]) * size
flags[0] = 0 # 1 is not prime
i = 1
while (2 * i + 1) ** 2 <= n:
if flags[i]:
p = 2 * i + 1
start = p * p // 2 # index of p squared
count = len(range(start, size, p))
flags[start::p] = bytes(count) # write zeros in one slice
i += 1
return [2] + [2 * i + 1 for i, f in enumerate(flags) if f]
print(odd_sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]The prime 2 is added back by hand because the array never represents it.
Step 3: Pack Eight Flags into Each Byte
A flag needs only one bit. A bit-packed sieve stores flag i in bit i & 7 of byte i >> 3. Combined with odd-only storage, each number costs 1/16 of a byte.
def bit_sieve(n):
if n < 2:
return []
m = (n + 1) // 2 # odd-only flag count
bits = bytearray([0xFF]) * ((m + 7) // 8)
def test(i):
return (bits[i >> 3] >> (i & 7)) & 1
def clear(i):
bits[i >> 3] &= ~(1 << (i & 7)) & 0xFF
clear(0) # 1 is not prime
i = 1
while (2 * i + 1) ** 2 <= n:
if test(i):
p = 2 * i + 1
for j in range(p * p // 2, m, p):
clear(j)
i += 1
return [2] + [2 * i + 1 for i in range(1, m) if test(i)]
print(bit_sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]In pure Python this version runs slower than odd_sieve, because every bit is cleared in a Python-level loop. In C, Rust, or with NumPy, bit packing is often faster too, because more of the array fits in the CPU cache.
Comparing the Options
| Representation | Bits per number | Memory for n = 10⁹ |
|---|---|---|
| Python `list` of bools | 64 | about 8 GB |
| `bytearray`, all numbers | 8 | about 1 GB |
| `bytearray`, odd only | 4 | about 500 MB |
| Bit-packed, odd only | 0.5 | about 62.5 MB |
None of these changes affects the O(n log log n) time bound. They only shrink the constant factor on memory, which stays O(n). To go below O(n) memory you need the segmented sieve, covered in the next chapter.
Exercise
In the odd-only sieve, what index holds the number 99, and what index does crossing out for p = 7 start at?
Show answer
99 is at index 99 // 2 = 49. For p = 7, crossing out starts at 7 * 7 = 49, which is at index 49 // 2 = 24, and then moves in index steps of 7.
Exercise
About how many bytes does a bit-packed, odd-only sieve need for n = 10⁸?
Show answer
It stores about 10⁸ / 2 = 5 × 10⁷ flags at one bit each, which is 5 × 10⁷ / 8 ≈ 6.25 × 10⁶ bytes, or about 6.25 MB.