Created
January 7, 2018 17:56
-
-
Save eisterman/b3905e5566388a41e5ec9771e2a94fce to your computer and use it in GitHub Desktop.
Inserisci in stdin la quantità di numeri in input e infine quali n-esimi numeri primi si vuole sapere
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
use std::io; | |
use std::fmt::Write; | |
/* | |
STDIN: | |
4 | |
7 1 199999 4 | |
STDOUT: | |
17 2 2750131 7 | |
*/ | |
fn main() { | |
let mut buffer = String::new(); | |
io::stdin().read_line(&mut buffer); | |
let q = buffer.trim().parse::<usize>().unwrap(); | |
buffer.clear(); | |
io::stdin().read_line(&mut buffer); | |
let texts : Vec<&str> = buffer.split_whitespace().collect(); | |
let mut indexes: Vec<u32> = Vec::with_capacity(q); | |
for t in texts.iter() { | |
indexes.push(t.trim().parse::<u32>().unwrap()); | |
} | |
let maxindex = *(indexes.iter().max().unwrap()) as usize; | |
let mut primes: Vec<u32> = Vec::with_capacity(maxindex); | |
primes.push(2); | |
let mut p = 3; | |
loop { | |
let limit = (p as f32).sqrt() as u32; | |
let mut isprime = true; | |
for controlp in (&primes).iter() { | |
if p % controlp == 0 { | |
isprime = false; | |
break; | |
} | |
if controlp > &limit { break; } | |
} | |
if isprime == true { | |
primes.push(p); | |
if primes.len() >= maxindex { | |
break; | |
} | |
} | |
p += 2; | |
} | |
let mut result = String::new(); | |
for req in indexes.iter() { | |
write!(&mut result, "{} ", primes[(req - 1) as usize]); | |
} | |
print!("{}", result.trim()); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment