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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.
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 aprimes
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 ofbool
, and adding toprimes
vector within the same loop.