Last active
August 29, 2015 14:02
-
-
Save jesuscast/6d84dfbe53aeb0f69eab to your computer and use it in GitHub Desktop.
Calculates the highest common factor in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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