patternrustMinor
Rust: Prime numbers
Viewed 0 times
rustnumbersprime
Problem
A first attempt to implement the Sieve of Eratosthenes to find all the prime numbers from 2 up to a given number resulted in this brute force algorithm. A user pointed out, that this is in fact not the Sieve of Eratosthenes, but just a brute force algorithm and should be reviewed as such.
#![feature(inclusive_range_syntax)]
pub fn primes_up_to(limit: u64) -> Vec {
let mut vec: Vec = (2...limit).collect::>();
for p in 2...limit {
vec.retain(|&x| x <= p || x % p != 0);
}
vec
}Solution
This seems pretty straight-forward, only minor nits:
- You don't need the turbofish on
collect; the type declaration on theletis enough of a hint.
- That type doesn't need to specify the type of the vector element, it can be inferred.
- Really reaching for straws, the
pandxvariables could be a bit longer, orx % p != 0could be made into a function with a name, just so that there's no mental overhead in reading the code.
pub fn primes_up_to(limit: u64) -> Vec {
let mut vec: Vec = (2...limit).collect();
for p in 2...limit {
vec.retain(|&x| x <= p || x % p != 0);
}
vec
}Code Snippets
pub fn primes_up_to(limit: u64) -> Vec<u64> {
let mut vec: Vec<_> = (2...limit).collect();
for p in 2...limit {
vec.retain(|&x| x <= p || x % p != 0);
}
vec
}Context
StackExchange Code Review Q#161992, answer score: 2
Revisions (0)
No revisions yet.