Prime Number generator in Rust

Hi,
as a little fun project I wrote this prime generator. It is not fully correct because I assume that 1 is not prime and 2 is prime.

fn main() {
    let mut primes = Vec::new();
    primes.push(2);
    let mut found = false;
    for n in 3..100 {
        for prime in &primes {
            if n % prime == 0 {
                found = true;
                break;
            }
        }
        if found == false {
            primes.push(n);
        }
        found = false;
    }
    println!("{:?}", primes);
}

Because it is a bit straight forward and I want to learn to write better Rust code maybe someone might help me to make this more idiomatic Rust. Don't be confused with the found variable. It means that I found a number that is NOT prime

Regards
Markus

For example

fn primes(max: u32) -> Vec<u32> {
    let mut primes = vec![2];
    for n in 3..max {
        if primes.iter().all(|p| n % p != 0) {primes.push(n);}
    }
    primes
}

fn main() {
    println!("{:?}", primes(100));
}
1 Like

What's incorrect about that assumption? In fact 1 is not prime and 2 is prime.

Don't mutate all over the place when all you need is to find whether there are divisors for a given number. Use the vec![] macro for creating a vector from a known set of elements.

fn main() {
    let mut primes = vec![2];

    for n in 3..100 {
        if primes.iter().all(|&p| n % p != 0) {
            primes.push(n);
        }
    }

    println!("{:?}", primes);
}
1 Like

Thanks for your answers. What confuses me is that H2CO3 uses &p, but both work as expected. Why?

This is pattern matching at work! The Book covers this topic in chapter 18.

The short version is that with the &p pattern, the p variable will be a copy of the number, just a simple u32. Without it, the type in the p variable will be &u32. And furthermore, because of Rust's Deref coercions, n % p still works in both cases, too!

1 Like

Thank you all. Really helpful. Continue to read chapter 18 :smile: