DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
guitarino profile image
Kirill Shestakov
fn main() {
    println!("{:?}", get_primes_up_to(200));
}

fn get_primes_up_to(n: usize) -> Vec<usize> {
    let start = 2;
    let end = n + 1;
    let mut crossed_out = vec![false; end - start + 1];
    let mut primes = Vec::new();
    for (i, number) in (start..end).enumerate() {
        if !crossed_out[i] {
            primes.push(number);
            for multiple in (2 * number..end).step_by(number) {
                crossed_out[multiple - start] = true;
            }
        }
    }
    return primes;
}
Enter fullscreen mode Exit fullscreen mode

This Rust code finds and prints the first 200 primes via a sieve method. Sieve method works by plotting all numbers from 2 to n and crossing out those numbers that are known multiple of each prime.

Sieve method illustration

In our code we create crossed_out vector. This vector will be responsible for holding the crossed out state of all numbers from 2 to n. We also create a primes vector that will hold our found primes. In a loop, we go through all numbers from 2 to n (inclusively), and if the number hasn't yet been crossed out, that means that this number is a prime. If it is a prime, we iterate over every multiple of that number up to n and cross it out from the list.

I like how expressive the code is thanks to Rust's range. At first I also used Rust's enums, options and iterators but then realized I could simplify the code by having crossed_out be a vector of bool, and adding to primes vector within the same loop.