There are different ways to calculate greatest common divisor in PHP. First try the recursive way to calculate greatest common divisor.
12| 16 | 1
| 12 |
----------
4 | 12 | 3
| 12 |
------------
0
So the GCD of 12 and 16 is: 4
function greatestCommonDivisor($num1, $num2){
$remainder = $num1 % $num2;
return ($remainder) ? greatestCommonDivisor($num2, $remainder) : $num2;
}
echo 'The GCD: ' . greatestCommonDivisor(12, 16);
The GCD: 4
Comments
Post a Comment