Created
December 23, 2015 11:51
-
-
Save mcjwsk/c028d4a272c0f2256469 to your computer and use it in GitHub Desktop.
math helper to sum fractions
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 | |
class Snowdog_Math_Helper_Data extends Mage_Core_Helper_Abstract | |
{ | |
/** | |
* Greatest common divisor using Euclid's algorithm | |
* | |
* @param int $a | |
* @param int $b | |
* @return int | |
*/ | |
public function gcd($a, $b) | |
{ | |
$a = abs($a); | |
$b = abs($b); | |
if ($a == 0) { | |
return $b; | |
} elseif ($b == 0) { | |
return $a; | |
} elseif ($a > $b) { | |
return $this->gcd($b, $a % $b); | |
} else { | |
return $this->gcd($a, $b % $a); | |
} | |
} | |
/** | |
* Least common multiple using Euclid's algorithm | |
* | |
* @param int $a | |
* @param int $b | |
* @return int | |
*/ | |
public function lcm($a, $b) | |
{ | |
$a = abs($a); | |
$b = abs($b); | |
if ($a > $b) { | |
return ($b / $this->gcd($a, $b)) * $a; | |
} else { | |
return ($a / $this->gcd($a, $b)) * $b; | |
} | |
} | |
/** | |
* Calculates the sum of fractions and round up to the ceiling | |
* | |
* @param array $fractions Array of items with the following format array(1, 2) | |
* @return int | |
*/ | |
public function sumFractions(array $fractions) | |
{ | |
$lcm = 0; | |
foreach ($fractions as $fraction) { | |
list(, $denominator) = $fraction; | |
if ($lcm === 0) { | |
$lcm = $denominator; | |
} else { | |
$lcm = $this->lcm($lcm, $denominator); | |
} | |
} | |
$nominatorSum = 0; | |
foreach ($fractions as $fraction) { | |
list($nominator, $denominator) = $fraction; | |
$multiplier = $lcm / $denominator; | |
$nominatorSum += $nominator * $multiplier; | |
} | |
return ceil($nominatorSum / $lcm); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment