HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMinor

Rust: Prime numbers

Submitted by: @import:stackexchange-codereview··
0
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 the let is 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 p and x variables could be a bit longer, or x % p != 0 could 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.