-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
43 lines (40 loc) · 1.02 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use std::io;
fn main() {
println!("Enter a limit to find all primes up to that limit:");
let mut limit = String::new();
io::stdin()
.read_line(&mut limit)
.expect("Failed to read line");
let limit: usize = match limit.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid input, please enter a valid number");
return;
}
};
let primes = find_primes(limit);
println!("Prime numbers up to {}:", limit);
for prime in primes {
println!("{}", prime);
}
}
fn find_primes(limit: usize) -> Vec<usize> {
let mut primes = vec![true; limit + 1];
primes[0] = false;
primes[1] = false;
let mut p = 2;
while p * p <= limit {
if primes[p] {
for i in (p * p..=limit).step_by(p) {
primes[i] = false;
}
}
p += 1;
}
primes
.iter()
.enumerate()
.filter(|(_, &is_prime)| is_prime)
.map(|(i, _)| i)
.collect()
}