[code] small improvements

* readability: changing variable names/adding variables for clarity
* initialize primes Vec with reasonable space to reduce allocations
* return type of find_next_prime more idiomatic (Option)
* avoid overflow by using checked_mul
This commit is contained in:
ddidderr 2024-02-09 22:38:11 +01:00
parent 2005b7d5ca
commit 1a7e57404e
Signed by: ddidderr
GPG Key ID: 3841F1C27E6F0E14

View File

@ -1,7 +1,7 @@
pub fn get_primes(max_nr: usize) -> Vec<u64> { pub fn get_primes(max_nr: usize) -> Vec<u64> {
let mut sieve = vec![true; max_nr + 1]; let mut sieve = vec![true; max_nr + 1];
let mut primes = Vec::new(); let mut primes = Vec::with_capacity(1_000_000);
sieve[0] = false; sieve[0] = false;
sieve[1] = false; sieve[1] = false;
@ -12,7 +12,7 @@ pub fn get_primes(max_nr: usize) -> Vec<u64> {
loop { loop {
check_off_multiples_of_nr(nr, &mut sieve); check_off_multiples_of_nr(nr, &mut sieve);
if !find_next_prime(&mut nr, &mut sieve) { if find_next_prime(&mut nr, &mut sieve).is_none() {
break; break;
} }
@ -22,24 +22,29 @@ pub fn get_primes(max_nr: usize) -> Vec<u64> {
primes primes
} }
fn find_next_prime(nr: &mut u64, sieve: &mut [bool]) -> bool { fn find_next_prime(nr: &mut u64, sieve: &mut [bool]) -> Option<u64> {
let start_idx = usize::try_from(*nr).ok()? + 1;
if let Some((idx, _)) = sieve if let Some((idx, _)) = sieve
.iter() .iter()
.enumerate() .enumerate()
.skip(usize::try_from(*nr).unwrap() + 1) .skip(start_idx)
.find(|(_, val)| **val) .find(|&(_, &is_prime)| is_prime)
{ {
*nr = idx as u64; *nr = idx as u64;
return true; return Some(*nr);
} }
false None
} }
fn check_off_multiples_of_nr(nr: u64, sieve: &mut [bool]) { fn check_off_multiples_of_nr(nr: u64, sieve: &mut [bool]) {
let nr = usize::try_from(nr).unwrap();
sieve sieve
.iter_mut() .iter_mut()
.skip(usize::try_from(nr * 2).unwrap()) .skip(nr.checked_mul(2).unwrap())
.step_by(usize::try_from(nr).unwrap()) .step_by(nr)
.for_each(|nr| *nr = false); .for_each(|nr| *nr = false);
} }