Calculate greatest common divisor using PHP

There are different ways to calculate greatest common divisor in PHP. First try the recursive way to calculate greatest common divisor.

Math example

Lets consider two numbers 12 and 16. Now first of all find out the GCD of these two numbers. 12| 16 | 1 | 12 | ---------- 4 | 12 | 3 | 12 | ------------ 0 So the GCD of 12 and 16 is: 4

PHP code snippet

function greatestCommonDivisor($num1, $num2){ $remainder = $num1 % $num2; return ($remainder) ? greatestCommonDivisor($num2, $remainder) : $num2; } echo 'The GCD: ' . greatestCommonDivisor(12, 16);

Output

The GCD: 4

Comments