public function Fraction::gcd in Fraction 7
Calculate the fraction's greatest common divisor using Euclid's algorithm.
Return value
string Returns the greatest common divisor.
1 call to Fraction::gcd()
- Fraction::reduce in ./
fraction.class.inc - Reduce the fraction to its simplest form.
File
- ./
fraction.class.inc, line 222 - Fraction class
Class
- Fraction
- @file Fraction class
Code
public function gcd() {
// Get the numerator and denominator.
$numerator = $this
->getNumerator();
$denominator = $this
->getDenominator();
// Make sure both numbers are positive.
$a = str_replace('-', '', $numerator);
$b = str_replace('-', '', $denominator);
// Euclid's algorithm gives us the greatest common divisor.
// Use BCMath's modulus function if available.
if (function_exists('bcmod')) {
while ($b != 0) {
$t = $b;
$b = bcmod($a, $b);
$a = $t;
}
}
else {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
}
return (string) $a;
}