Sieve of Eratosthenes

The rust dig deeper into sieve page shows this solution:


But this solution has a problem in the line 3:

work[1] = 0;

If the value of upper_bound is zero, the program panics instead of returning an empty Vec. I suggest to add a test to check if it correctly works with the number zero like is one to check the number one:

//This one already exists
#[test]
fn no_primes_under_two() {
    let input = 1;
    let output = primes_up_to(input);
    let expected = [];
    assert_eq!(output, expected);
}

//This one don't exists
#[test]
fn no_primes_under_one() {
    let input = 0;
    let output = primes_up_to(input);
    let expected = [];
    assert_eq!(output, expected);
}

Thanks for the report. This is not Rust-specific, because the tests are coming from problem-specifications. If such a test were to be added, it would be there. But I doubt the test would be accepted, because we don’t want all exercises to become about error handling and input validation. The point of this exercise is not to teach input validation.

2 Likes