I think I have just written the ugliest code in my life

55 points Popular_Tour1811

I've been trying to make a simple Eratosthenes sieving function, not batched nor parallelized.

I finished it now, and it looks very fucking ugly.

I tried removing the \loop\\ and only use a for loop, but the compiler complained because it was holding a reference to the vec I was changing inside of it.

Here is the offender (it is also 47 lines long):

fn primes_up_to(i: usize) -> Vec<u64> {
    if i <= 2 {
        panic!("cant generate primes < 2");
    }

    let mut current_index = 0;

    // represents if  a given number is prime
    // starts at 1
    let mut numbers_is_prime = vec![true; i];

    numbers_is_prime[0] = false; // 1 is not prime or else this will break

    loop {
        current_index += 1;

        // don't go off bounds
        if current_index >= i - 1 {
            break;
        }

        // don't procede if it isn't a prime number
        if !numbers_is_prime[current_index] {
            continue;
        }

        // current index is an array index
        // to get the actual number we have to sum 1
        for number in numbers_is_prime
            .iter_mut()
            .skip(current_index) // will skip to the actual number
            .step_by(current_index + 1)
        {
            *number = false;
        }
    }

    let mut numbers: Vec<u64> = vec![];

    for (idx, is) in numbers_is_prime.into_iter().enumerate() {
        if is {
            numbers.push((idx + 1).try_into().unwrap())
        }
    }

    numbers
}

Can someone please aid me in understanding why does it look so horrendous, and what can I do to fix it?

I have done the same thing in C++, a language I know way less about, and it was prettier.

Thanks!

EDIT: forgot to add, but it works, as incredible as it seems