public function Fraction::gcd in Fraction 8
Same name and namespace in other branches
- 2.x src/Fraction.php \Drupal\fraction\Fraction::gcd()
Calculate the fraction's greatest common divisor using Euclid's algorithm.
Return value
string Returns the greatest common divisor.
Overrides FractionInterface::gcd
1 call to Fraction::gcd()
- Fraction::reduce in src/
Fraction.php - Reduces the fraction to its simplest form.
File
- src/
Fraction.php, line 190
Class
- Fraction
- A simple class for representing and acting upon a fraction.
Namespace
Drupal\fractionCode
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;
}