find the least common multiple of a list of numbers in php

You can find the least common multiple (LCM) of a list of numbers by using a function that computes the LCM of two numbers and applies it to the list of numbers. Here's an implementation in PHP:

main.php
/**
 * Computes the least common multiple (LCM) of two numbers.
 */
function lcm($a, $b)
{
    return ($a * $b) / gcd($a, $b);
}

/**
 * Computes the greatest common divisor (GCD) of two numbers.
 */
function gcd($a, $b)
{
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}

/**
 * Computes the least common multiple (LCM) of a list of numbers.
 * Assumes the list contains at least one element.
 */
function lcm_list(array $numbers)
{
    $result = $numbers[0];
    for ($i = 1; $i < count($numbers); ++$i) {
        $result = lcm($result, $numbers[$i]);
    }
    return $result;
}
634 chars
34 lines

The lcm_list function takes an array of numbers and iteratively computes their LCM. It uses the lcm function, which computes the LCM of two numbers, and the gcd function, which computes the GCD of two numbers (needed to compute the LCM).

related categories

gistlibby LogSnag