Created
August 2, 2015 20:57
-
-
Save barosl/c0738cf7ca38236bebf2 to your computer and use it in GitHub Desktop.
Naive prime number generation in Rust
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
//! 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