Prime Sieve Of Eratosthenes Segmented (Rust)
Generate all primes up to n in Rust using a segmented sieve of Eratosthenes for memory efficiency.
Code
fn segmented_sieve(n: usize) -> Vec<usize> {
if n < 2 { return vec![]; }
let limit = (n as f64).sqrt() as usize + 1;
let mut base_primes = vec![];
let mut is_comp = vec![false; limit];
for i in 2..limit { if !is_comp[i] { base_primes.push(i); for j in (i*i..limit).step_by(i) { is_comp[j] = true; } } }
let mut primes = base_primes.clone();
let seg_size = 1 << 15;
for low in (limit..=n).step_by(seg_size) {
let high = (low + seg_size - 1).min(n);
let mut seg = vec![false; high - low + 1];
for &p in &base_primes { let start = ((low + p - 1) / p) * p; for j in (start..=high).step_by(p) { seg[j - low] = true; } }
for i in 0..seg.len() { if !seg[i] && low + i >= 2 { primes.push(low + i); } }
}
primes
}What the code does
Prime Sieve Of Eratosthenes Segmented (Rust) is built around the function segmented_sieve.
Repetition is confined to for i in 2..limit { if !is_comp[i] { base_primes.push(i); for j in (i*i..limit).step_by(i) { is_c… — the rest of the file is straight-line.
Using it
The entry-point signature is fn segmented_sieve(n: usize) -> Vec<usize>
segmented_sieve is the public entry point; everything else in the file exists to support it.
Key statements
if n < 2 { return vec![]; }
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `segmented_sieve` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.