Created
January 30, 2016 16:12
-
-
Save mrageh/391dc85080db2a7d994e to your computer and use it in GitHub Desktop.
Basic implementation of Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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