Skip to content

Instantly share code, notes, and snippets.

@bananaumai
Last active March 24, 2019 15:01
Show Gist options
  • Select an option

  • Save bananaumai/c8b167b8a885853a35b2b3c33abd08f1 to your computer and use it in GitHub Desktop.

Select an option

Save bananaumai/c8b167b8a885853a35b2b3c33abd08f1 to your computer and use it in GitHub Desktop.
rust code example - find prime numbers
use std::collections::HashMap;
fn primes(n: usize) -> Vec<usize> {
if n < 2 {
return vec![];
}
if n == 2 {
return vec![2];
}
let mut odds = Vec::new();
let mut i = 3;
while i <= n {
odds.push(i);
i += 2;
}
let mut factors = HashMap::new();
factors.insert(2, true);
for n in &odds {
factors.insert(*n, true);
}
for i in &odds {
if !*(factors.get(i).unwrap()) {
continue;
}
let mut k = *i + 2;
while k <= n {
if k % *i == 0 {
factors.insert(k, false);
}
k += 2;
}
}
let mut result = factors.into_iter().filter(|(_, v)| *v).map(|(k, _)| k).collect::<Vec<usize>>();
result.sort();
result
}
fn main() {
// primes
assert_eq!(primes(2), vec![2]);
assert_eq!(primes(3), vec![2, 3]);
assert_eq!(primes(5), vec![2, 3, 5]);
assert_eq!(primes(13), vec![2, 3, 5, 7, 11, 13]);
assert_eq!(primes(30), vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment