Skip to content

Instantly share code, notes, and snippets.

@jameshartig
Created January 31, 2014 03:33
Show Gist options
  • Save jameshartig/8726217 to your computer and use it in GitHub Desktop.
Save jameshartig/8726217 to your computer and use it in GitHub Desktop.
<?php
function gcd($a, $b) {
$a = abs($a);
$b = abs($b);
if ($a < $b) {
$c = $a;
$a = $b;
$b = $c;
}
if ($b == 0) {
return $a;
}
$r = $a % $b;
while ($r > 0) {
$a = $b;
$b = $r;
$r = $a % $b;
}
return $b;
}
function simplify($ar) {
$a = null;
foreach ($ar as $b) {
if (is_null($a)) {
$a = $b;
continue;
}
$a = gcd($a, $b);
if ($a <= 1) {
return $ar;
}
}
foreach ($ar as &$val) {
$val = $val / $a;
}
return $ar;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment