find the least common multiple of two numbers in php

One way to find the least common multiple (LCM) of two numbers in PHP is to use the following algorithm:

  1. Find the greatest common divisor (GCD) of the two numbers using the Euclidean algorithm.
  2. Calculate the product of the two numbers.
  3. Divide the product by the GCD to get the LCM.

Here's the PHP code to implement this algorithm:

main.php
function findGCD($a, $b) {
    // base case
    if ($b == 0) {
        return $a;
    }
    // recursive case
    return findGCD($b, $a % $b);
}

function findLCM($a, $b) {
    $gcd = findGCD($a, $b);
    $lcm = ($a * $b) / $gcd;
    return $lcm;
}

// example usage
$a = 6;
$b = 8;
$lcm = findLCM($a, $b);
echo "The LCM of $a and $b is: $lcm";
345 chars
21 lines

This will output: "The LCM of 6 and 8 is: 24".

gistlibby LogSnag