Hey lovely Rust community,
I am starting to learn Rust and one of my first programs I write in every language I try to learn is a prim finder(sieve of Eratosthenes) because it always leave some room for improvements and tweaks, even being quite simple in terms of complexity.
I am thankful for every critique you might give me.
use std::io::{stdin, stdout, Write};
//read user input and returns it as String
fn read() -> usize {
let mut input = String::new();
stdout().flush()
.expect("failed to flush");
stdin().read_line(&mut input)
.expect("failed to read");
return input.trim().parse().unwrap();
}
struct BoolList {
table :Vec<bool>
}
impl BoolList {
fn new() -> Self {
BoolList {
table: Vec::new()
}
}
//fill the list with true values (assuming each number is prim in the beginning)
fn fill_vec(&mut self, int: usize) {
for _i in 0..int {
self.table.push(true);
}
}
//set the position to false
fn set_false(&mut self, pos :usize) {
self.table[pos] = false;
}
//set all multiples of val to false
fn iter_value(&mut self, value :usize) {
let mut coof :usize = 2;
if self.table[value] == true {
while value * coof < self.table.len() {
self.set_false(value * coof);
coof += 1;
}
}
}
}
//iterate over each value in the list and change multiples to false
fn iter_list(list :&mut BoolList) {
for num in 2..list.table.len() {
list.iter_value(num);
}
}
fn pretty_print(list :&BoolList) {
for num in 2..list.table.len() {
if list.table.get(num) == Some(&true) {
println!("prim: {}",num);
}
}
}
pub fn main() {
let mut prim_list = BoolList::new();
println!("what should be the prim bound?");
//fills empty prim list assuming that every number is prim at start
//with users input as upper bound
prim_list.fill_vec(read());
//unvalue all numbers which aren't prim
iter_list(&mut prim_list);
//print list
pretty_print(&prim_list);
}