Saturday, January 9, 2010: HCF Function in PHP « from the old blog archive »

I just learned more about recursive functions.

So I made this little function in PHP.

function hcf($a, $b) {
    if ($b > $a) return hcf($b, $a);
    if ($b == 0) return $a;
    return hcf($b, $a % $b);

function hcf_array($array) {
    if (count($array) < 1) return false;
    if (count($array) == 1) return $array[0];
    array_unshift ($array, hcf(array_shift($array), array_shift($array)));
    return hcf_array($array);

Function hcf($a, $b) finds the HCF of $a and $b.

Function hcf_array($a) finds the HCF of array $a.

May be useful in the future.