Skip to content

Instantly share code, notes, and snippets.

@dan-c-underwood
Last active August 29, 2015 13:57
Show Gist options
  • Save dan-c-underwood/9821776 to your computer and use it in GitHub Desktop.
Save dan-c-underwood/9821776 to your computer and use it in GitHub Desktop.
Rust implementation of sieve of Eratosthenes
use std::env;
fn main() {
//Get range from command line (primes in range 1..input)
let num = env::args().nth(1).unwrap();
let max: usize = match num.parse() {
Ok(n) => {
n
},
Err(_) => {
println!("Error: not a valid number!");
return;
}
};
let mut primes = Vec::with_capacity(max);
let mut items_pushed = 0;
loop {
primes.push(true);
items_pushed += 1;
if items_pushed == max {
break;
}
}
primes[0] = false;
if max > 1 {
primes[1] = false;
}
for i in 0..max {
if primes[i] {
let mut mult = i << 1;
while mult < max {
primes[mult] = false;
mult += i;
}
}
}
let mut found_primes = 0;
for &prime in primes.iter() {
if prime {
found_primes += 1;
}
}
println!("Number of primes: {}", found_primes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment