Skip to content

Instantly share code, notes, and snippets.

@jesuscast
Last active August 29, 2015 14:02
Show Gist options
  • Save jesuscast/6d84dfbe53aeb0f69eab to your computer and use it in GitHub Desktop.
Save jesuscast/6d84dfbe53aeb0f69eab to your computer and use it in GitHub Desktop.
Calculates the highest common factor in an array
<?php
function highestCommonFactor($array){
$hcf = 1;
$totalItems = count($array);
$smaller = $array[$totalItems-1];
for($i = 0; $i<$totalItems; $i++){
$temp = $array[$i];
if($array[$i]<0) {
$temp = -1*$temp;
}
if($temp<$smaller) {
$smaller = $array[$i];
}
}
//echo("Smaller ".$smaller);
for($i = 1; $i<=($smaller+1); $i++){
for($j = 0; $j<$totalItems; $j++){
//echo(" 0-".$array[$j]."-".($array[$j]%$i==0)."-".$i."- ");
if(!($array[$j]%$i==0)){
break;
//echo("break at ".$array[$j]);
}
if($j==($totalItems-1)){
$hcf = $i;
//echo("assign at at ".$array[$j]. " hcf = ".$hcf);
}
//echo(" 1-".$array[$j]."-".($array[$j]%$i==0)."-".$i."- ");
}
}
return $hcf;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment