Skip to content

Commit f9baf6e

Browse files
committed
ref: optimize implementation a bit more
1 parent 502cb8a commit f9baf6e

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/math/sieve_of_eratosthenes.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,46 +18,49 @@ pub fn sieve_of_eratosthenes(num: usize) -> Vec<usize> {
1818

1919
let end: usize = (num as f64).sqrt() as usize;
2020

21-
// mark non-prime numbers in the sieve
22-
update_sieve(&mut sieve, end, num);
21+
// Mark non-prime numbers in the sieve and collect primes up to `end`
22+
update_sieve(&mut sieve, end, num, &mut result);
2323

24-
// collect all prime numbers
25-
result = extract_primes(&sieve);
24+
// Collect remaining primes beyond `end`
25+
result.extend(extract_remaining_primes(&sieve, end + 1));
2626
}
2727
result
2828
}
2929

30-
/// Marks non-prime numbers in the sieve.
30+
/// Marks non-prime numbers in the sieve and collects prime numbers up to `end`.
3131
///
3232
/// # Arguments
3333
///
34-
/// * `sieve` - A mut slice of booleans representing the sieve.
34+
/// * `sieve` - A mutable slice of booleans representing the sieve.
3535
/// * `end` - The square root of the upper limit, used to optimize the algorithm.
3636
/// * `num` - The upper limit up to which to mark non-prime numbers.
37-
fn update_sieve(sieve: &mut [bool], end: usize, num: usize) {
37+
/// * `result` - A mutable vector to store the prime numbers.
38+
fn update_sieve(sieve: &mut [bool], end: usize, num: usize, result: &mut Vec<usize>) {
3839
for start in 2..=end {
3940
if sieve[start] {
41+
result.push(start); // Collect prime numbers up to `end`
4042
for i in (start * start..=num).step_by(start) {
4143
sieve[i] = false;
4244
}
4345
}
4446
}
4547
}
4648

47-
/// Extracts prime numbers from the sieve.
49+
/// Extracts remaining prime numbers from the sieve beyond the given start index.
4850
///
4951
/// # Arguments
5052
///
5153
/// * `sieve` - A slice of booleans representing the sieve with non-prime numbers marked as false.
54+
/// * `start` - The index to start checking for primes (inclusive).
5255
///
5356
/// # Returns
5457
///
55-
/// A vector containing all prime numbers extracted from the sieve.
56-
fn extract_primes(sieve: &[bool]) -> Vec<usize> {
57-
sieve
58+
/// A vector containing all remaining prime numbers extracted from the sieve.
59+
fn extract_remaining_primes(sieve: &[bool], start: usize) -> Vec<usize> {
60+
sieve[start..]
5861
.iter()
5962
.enumerate()
60-
.filter_map(|(num, is_prime)| if *is_prime { Some(num) } else { None })
63+
.filter_map(|(i, &is_prime)| if is_prime { Some(start + i) } else { None })
6164
.collect()
6265
}
6366

0 commit comments

Comments
 (0)