find the greatest common divisor of two numbers in php

You can find the greatest common divisor (GCD) of two numbers in PHP using the Euclidean algorithm. Here's a function that does that:

main.php
function gcd($a, $b) {
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}
124 chars
9 lines

Here's how it works:

  1. Start with two numbers, $a and $b.
  2. While $b is not zero, set $t equal to $b, $b equal to the remainder of $a divided by $b, and $a equal to $t.
  3. When $b becomes zero, the GCD is the value of $a.

You can use this function like this:

main.php
echo gcd(10, 25); // outputs 5
echo gcd(14, 28); // outputs 14
echo gcd(17, 23); // outputs 1
94 chars
4 lines

related categories

gistlibby LogSnag