How can PHP be used to compare two numbers in a fraction format like 1/10?
When comparing two numbers in fraction format like 1/10 in PHP, you need to convert the fractions into a common denominator before comparing them. One way to do this is by finding the least common multiple (LCM) of the denominators and then converting both fractions to have the same denominator. Once the fractions have the same denominator, you can compare the numerators to determine which fraction is larger.
function compareFractions($numerator1, $denominator1, $numerator2, $denominator2) {
$lcm = $denominator1 * $denominator2 / gcd($denominator1, $denominator2);
$newNumerator1 = $numerator1 * ($lcm / $denominator1);
$newNumerator2 = $numerator2 * ($lcm / $denominator2);
if ($newNumerator1 > $newNumerator2) {
return 1;
} elseif ($newNumerator1 < $newNumerator2) {
return -1;
} else {
return 0;
}
}
function gcd($a, $b) {
return $b == 0 ? $a : gcd($b, $a % $b);
}
// Example usage
$result = compareFractions(1, 10, 3, 10);
if ($result == 1) {
echo "1/10 is greater than 3/10";
} elseif ($result == -1) {
echo "1/10 is less than 3/10";
} else {
echo "1/10 is equal to 3/10";
}