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

To find the greatest common divisor of a list of numbers in PHP, we can write a function that uses the Euclidean algorithm.

main.php
/**
 * Calculate greatest common divisor of a list of numbers.
 *
 * @param array $numbers
 * @return int
 */
function gcd(array $numbers) : int {
    $result = $numbers[0];
    $count = count($numbers);
    for($i = 1; $i < $count; $i++) {
        $result = gcdTwo($result, $numbers[$i]);
    }
    return $result;
}

/**
 * Calculate greatest common divisor of two numbers.
 *
 * @param int $a
 * @param int $b
 * @return int
 */
function gcdTwo(int $a, int $b) : int {
    while($b) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}
567 chars
31 lines

This function takes an array of numbers and calculates the GCD of all the numbers in the array using the gcdTwo function, which takes two numbers and returns their GCD. The gcd function uses a loop to iterate over all the numbers in the array and keep track of the GCD so far.

related categories

gistlibby LogSnag