Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Naive prime number generation in Rust
//! Conforms to the input data format of http://www.spoj.com/problems/PRIME1/ but not usable as a
//! solution due to the slowness of the algorithm
use std::io::{stdin, BufRead};
use std::error::Error;
fn get_line<R: BufRead>(r: &mut R) -> Result<String, Box<Error>> {
let mut line = String::new();
try!(r.read_line(&mut line));
Ok(line)
}
fn is_prime(num: i32) -> bool {
if num < 2 { return false; }
let root = (num as f64).sqrt() as i32;
for i in 2..root+1 {
if num % i == 0 { return false; }
}
true
}
fn check_range(a: i32, b: i32) {
for i in a..b+1 {
if is_prime(i) {
println!("{}", i);
}
}
}
fn go() -> Result<(), Box<Error>> {
let stdin = stdin();
let mut stdin = stdin.lock();
let cnt = try!(try!(get_line(&mut stdin)).trim().parse::<i32>());
for _ in 0..cnt {
let line = try!(get_line(&mut stdin));
let mut it = line.split_whitespace();
match (it.next(), it.next()) {
(Some(a), Some(b)) => check_range(try!(a.parse::<i32>()), try!(b.parse::<i32>())),
_ => panic!("Invalid format"),
}
println!("");
}
Ok(())
}
fn main() {
go().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.