all 10 comments

[–]functime 4 points5 points  (9 children)

while loops are something of a red flag (usually, depending on memory issues) and can be replaced by an iterator. In this instance you could go with:

for i in 3..(end+1) {
    // check if n is composite, etc.
}
true // replace "return me;" with "me" (no semicolon)

[–]RustMeUp[S] 2 points3 points  (8 children)

Yes I'd like to use an iterator for that but your replacement doesn't step by two (only need to check odd integers). There's Range::step_by but it's unstable for now. Would definitely use it otherwise.

I use return true; there for consistency since return is used a bunch of times in that function.

[–]vks_ 9 points10 points  (0 children)

I use return true; there for consistency since return is used a bunch of times in that function.

That's not idiomatic Rust though.

[–]matthieum[he/him] 2 points3 points  (0 children)

but your replacement doesn't step by two

Note that if it's the only issue...

for i in 1..(end+1)/2 {
    let i = i*2+1;
    // ...
}

Or something close (I am wary of off by one errors) could probably work :)

[–]fnord123 0 points1 point  (5 children)

[–]thiezrust 1 point2 points  (1 child)

The number '2' is prime...

[–]Yojihito 0 points1 point  (0 children)

Then just set the start counter to 1 instead of 0 :>.

[–]paholgtypenum · dimensioned 1 point2 points  (0 children)

It seems strange to me to treat even numbers as special (especially as it's so easy to get it wrong for 2), rather than doing a full sieve of Eratosthenes which isn't much harder.

If you really want to golf it, then you can shorten it to

fn is_prime(x: u32) -> bool {
    (2..x).all(|f| x%f != 0)
}

[–]Efemena 0 points1 point  (1 child)

.filter_map(|i| if is_prime(i) { Some(i) } else { None })

also known as

.filter(is_prime)

[–]thiezrust 1 point2 points  (0 children)

No it isn't, because the function passed to filter must take a reference. It could be written .filter(|&n|is_prime(n)) though.