Skip to main content

lib_jsl_number_theory/
prime_sieves.rs

1//! Prime sieves.
2//!
3//! See the book entry [Primes: sieves, Miller–Rabin and factorisation](https://jwkunz.github.io/lib_jsl/book/number-theory/primes.html).
4
5/// All primes `≤ n` by the sieve of Eratosthenes over odd numbers only (`n/16` bytes of
6/// work space as a bit set), in `O(n log log n)` time.
7pub fn sieve_of_eratosthenes(n: u64) -> Vec<u64> {
8    if n < 2 {
9        return Vec::new();
10    }
11    // Bit i represents the odd number 2i + 1.
12    let count = n.div_ceil(2) as usize;
13    let mut composite = vec![0u64; count.div_ceil(64)];
14    // ANCHOR: eratosthenes
15    let mut i = 1usize;
16    while (2 * i + 1) * (2 * i + 1) <= n as usize {
17        if composite[i / 64] >> (i % 64) & 1 == 0 {
18            let p = 2 * i + 1;
19            let mut j = (p * p) / 2;
20            while j < count {
21                composite[j / 64] |= 1 << (j % 64);
22                j += p;
23            }
24        }
25        i += 1;
26    }
27    // ANCHOR_END: eratosthenes
28    let mut primes = vec![2];
29    primes.extend((1..count).filter(|&i| composite[i / 64] >> (i % 64) & 1 == 0).map(|i| (2 * i + 1) as u64));
30    primes
31}
32
33/// All primes in `[low, high]` by a segmented sieve: base primes up to `√high` cross off a
34/// window of the requested range only, so the memory is `O(√high + (high − low))`. The base
35/// sieve dominates the cost for very large `high` (it reaches 2³² near `u64::MAX`).
36pub fn segmented_sieve(low: u64, high: u64) -> Vec<u64> {
37    if high < 2 || low > high {
38        return Vec::new();
39    }
40    let low = low.max(2);
41    let root = crate::integer_square_root::integer_square_root_newton(high as u128) as u64;
42    let base = sieve_of_eratosthenes(root);
43    let width = (high - low + 1) as usize;
44    let mut composite = vec![false; width];
45    for &p in &base {
46        // First multiple of p in the window, never p itself (none if it would pass u64::MAX).
47        let Some(first) = low.div_ceil(p).checked_mul(p) else { continue };
48        let start = (p * p).max(first);
49        let mut m = start;
50        while m <= high {
51            composite[(m - low) as usize] = true;
52            match m.checked_add(p) {
53                Some(next) => m = next,
54                None => break,
55            }
56        }
57    }
58    (0..width).filter(|&i| !composite[i]).map(|i| low + i as u64).collect()
59}
60
61/// The prime-counting function `π(n)`.
62pub fn prime_count(n: u64) -> usize {
63    sieve_of_eratosthenes(n).len()
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    fn trial(n: u64) -> bool {
71        n >= 2 && (2..).take_while(|d| d * d <= n).all(|d| !n.is_multiple_of(d))
72    }
73
74    #[test]
75    #[ignore = "slow: sieves the base primes up to 2^32 (about 25 s in release)"]
76    fn the_top_of_the_u64_range_sieves_without_overflow() {
77        // The three largest 64-bit primes are 2^64 − 95, 2^64 − 83 and 2^64 − 59; first multiples
78        // near u64::MAX used to overflow.
79        assert_eq!(segmented_sieve(u64::MAX - 100, u64::MAX), vec![u64::MAX - 94, u64::MAX - 82, u64::MAX - 58]);
80    }
81
82    #[test]
83    fn sieve_matches_trial_division_and_known_counts() {
84        let primes = sieve_of_eratosthenes(10_000);
85        assert_eq!(primes, (0..=10_000).filter(|&n| trial(n)).collect::<Vec<_>>());
86        assert_eq!(prime_count(1_000_000), 78_498);
87        assert_eq!(prime_count(10_000_000), 664_579);
88        assert!(sieve_of_eratosthenes(1).is_empty() && sieve_of_eratosthenes(2) == vec![2] && sieve_of_eratosthenes(9) == vec![2, 3, 5, 7]);
89    }
90
91    #[test]
92    fn segmented_sieve_matches_and_reaches_large_ranges() {
93        assert_eq!(segmented_sieve(0, 100), sieve_of_eratosthenes(100));
94        let window = segmented_sieve(999_000, 1_000_100);
95        assert_eq!(window, sieve_of_eratosthenes(1_000_100).into_iter().filter(|&p| p >= 999_000).collect::<Vec<_>>());
96        // The primes just above 10¹² (known: 10¹² + 39 and 10¹² + 61).
97        let near = segmented_sieve(1_000_000_000_000, 1_000_000_000_100);
98        assert_eq!(&near[..2], &[1_000_000_000_039, 1_000_000_000_061]);
99        assert!(segmented_sieve(20, 10).is_empty() && segmented_sieve(0, 1).is_empty());
100        // Near 10¹⁵ the base primes only reach 3.2 · 10⁷; the first prime is 10¹⁵ + 37.
101        let high = segmented_sieve(1_000_000_000_000_000, 1_000_000_000_001_000);
102        assert_eq!(high[0], 1_000_000_000_000_037);
103    }
104}