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.rs262 chars16 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.rs108 chars4 lines
This will output:
main.rs30 chars2 lines
gistlibby LogSnag