find the greatest common divisor of a list of numbers in rust

To find the greatest common divisor (GCD) of a list of numbers in Rust, we can use the Euclidean algorithm, which relies on the fact that the GCD of two numbers can be computed by repeatedly subtracting the smaller number from the larger number until the two numbers are equal.

To extend this to a list of numbers, we can simply apply the Euclidean algorithm to pairs of adjacent numbers in the list until we have a single GCD left.

Here's an implementation in Rust that takes a vector nums of integers as input and returns their GCD:

main.rs
fn gcd(a: i32, b: i32) -> i32 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn gcd_list(nums: &Vec<i32>) -> i32 {
    let mut result = nums[0];
    for &num in nums.iter().skip(1) {
        result = gcd(result, num);
    }
    result
}
262 chars
16 lines

The gcd function implements the Euclidean algorithm to compute the GCD of two numbers.

The gcd_list function takes a reference to a vector of integers, and initializes the result to the first element of the vector. It then iterates over the remaining elements of the vector, updating the result by taking the GCD of the current result and the current element.

We can call this function like this:

main.rs
let nums = vec![12, 24, 36];
let result = gcd_list(&nums);
println!("The GCD of {:?} is {}", nums, result);
108 chars
4 lines

This will output:

main.rs
The GCD of [12, 24, 36] is 12
30 chars
2 lines

related categories

gistlibby LogSnag