How to find all divisors of a number in Rust

1 Answer

0 votes
/*
 * Function: find_divisors
 * Purpose: Efficiently find all divisors of a number using sqrt(n).
 *
 * Explanation:
 *   - We loop only up to sqrt(n), which reduces the number of iterations.
 *   - If i divides n, then both i and n / i are divisors.
 *   - If i == n / i (perfect square), we add it only once.
 *   - Finally, we sort the list so the divisors appear in ascending order.
 */
fn find_divisors(n: i32) -> Vec<i32> {
    let mut divisors: Vec<i32> = Vec::new();
    let limit: i32 = (n as f64).sqrt() as i32;

    for i in 1..=limit {
        if n % i == 0 {
            divisors.push(i); // Add the smaller divisor

            let pair: i32 = n / i;
            if i != pair {
                divisors.push(pair); // Add the paired divisor
            }
        }
    }

    divisors.sort();

    divisors
}

fn main() {
    let num: i32 = 24;

    let result: Vec<i32> = find_divisors(num);

    print!("Divisors of {}: [", num);
    for (index, value) in result.iter().enumerate() {
        print!("{}", value);
        if index < result.len() - 1 {
            print!(", ");
        }
    }
    println!("]");
}



/*
run:

Divisors of 24: [1, 2, 3, 4, 6, 8, 12, 24]

*/

 



answered 4 days ago by avibootz
...