Skip to content

Instantly share code, notes, and snippets.

@mrageh
Created January 30, 2016 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrageh/391dc85080db2a7d994e to your computer and use it in GitHub Desktop.
Save mrageh/391dc85080db2a7d994e to your computer and use it in GitHub Desktop.
Basic implementation of Sieve of Eratosthenes
/// Find all prime numbers less than `n`.
/// For example, `sieve(7)` should return `[2, 3, 5]`
pub fn sieve(n: usize) -> Vec<usize> {
let mut p:usize = 2;
let range = p..n;
let mut list:Vec<usize> = vec![];
//build list
for x in range {
list.push(x);
}
// go through the list
// check multiples of P are less then n and not in list
// if in list remove them
// reassign the next element in the iteration as p
for i in p..list.len() {
for j in p..list.len() {
let multiple_of_p = p * j;
let multiple_of_p_in_list = list.contains(&multiple_of_p);
if multiple_of_p < n && multiple_of_p_in_list {
let index = list.iter().position(|x| *x == multiple_of_p).unwrap();
list.remove(index);
}
}
p = i;
}
list
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment