Skip to content

Instantly share code, notes, and snippets.

@svelleweetakealot
Created January 17, 2018 20:49
Show Gist options
  • Save svelleweetakealot/b50b66c841ea61e5ba73549072a7b80c to your computer and use it in GitHub Desktop.
Save svelleweetakealot/b50b66c841ea61e5ba73549072a7b80c to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
//
// Let A be an array of Boolean values, indexed by integers 2 to n,
// initially all set to true.
//
// for i = 2, 3, 4, ..., not exceeding √n:
// if A[i] is true:
// for j = i**2, i**2+i, i**2+2i, i**2+3i, ..., not exceeding n:
// A[j] := false.
//
// Output: all i such that A[i] is true.
fn sieve(n: u32) -> Vec<usize> {
let mut checks: Vec<bool> = vec![true; (n + 1) as usize];
let max_val = (((n as f32).sqrt()).round() as u32);
for i in 2..max_val {
let mut counter = 0;
if checks[i as usize] == true {
loop {
let j = i.pow(2) + counter * i;
counter += 1;
if j > n {
break
}
checks[j as usize] = false;
}
}
}
let vec: Vec<usize> = checks
.iter()
.enumerate()
.filter(| &(_, b) | { *b })
.map(| (a, _) | { a })
.collect();
vec
}
fn main() {
println!("{:?}", sieve(1346));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment