Core\Math::lcm
Finds the least common multiple of two whole numbers. This is the smallest positive number that both of them divide with no remainder. For 4 and 6, the result is 12.
The signs of the two numbers do not change the result, and the result is never negative. When one of the numbers is 0, the result is 0. When the result is bigger than Core\Math::INT_MAX, the call throws an ArithmeticError. This happens quickly for two big numbers that share no divisor.
Use it to find when two things that repeat at different intervals happen together again. Core\Math::gcd finds the largest number that divides both numbers.
The examples below show a few pairs of numbers, then a result that is too big for an int, then when two scheduled jobs next run in the same minute.
Parameters
$aintThe first integer. Its sign does not change the result.$bintThe second integer. Its sign does not change the result.
Return value
Returns int. The least common multiple, which is never negative. When one integer is 0, the result is 0.
Errors
ArithmeticErrorWhen the result is bigger thanCore\Math::INT_MAX. This happens quickly for two big integers that share no divisor.
Examples
A few pairs
<?nvs// Shows the least common multiple of a few pairs of numbers.
// 12 is the smallest number that both 4 and 6 divide. This prints 12.echo Core\Math::lcm(4, 6), "\n";
// The signs do not change the result, and it is never negative. This prints 12.echo Core\Math::lcm(-4, 6), "\n";
// When one number is 0, the result is 0.echo Core\Math::lcm(5, 0), "\n";12120A result too big
<?nvs// Shows what happens when the result is too big for an `int`.
// A number divides itself, so the result is the number. This prints 9223372036854775807.echo Core\Math::lcm(Core\Math::INT_MAX, Core\Math::INT_MAX), "\n";
// The result would be two times `Core\Math::INT_MAX`.// That does not fit an `int`, so the call throws an `ArithmeticError`.try { echo Core\Math::lcm(Core\Math::INT_MAX, 2), "\n";} catch (ArithmeticError $error) { echo "The result is too big.\n";}9223372036854775807The result is too big.Jobs in the same minute
<?nvs// Shows how to find when two jobs that repeat at different intervals run in the same minute again.
class Schedule{ // Both jobs start at minute 0. They run together again after the least common multiple. public static function describe(int $first, int $second): void { int $minutes = Core\Math::lcm($first, $second); echo 'Every ', $first, ' and every ', $second, ' minutes: together after ', $minutes, " minutes\n"; }}
// This prints 30 minutes.Schedule::describe(6, 15);
// 5 divides 10, so the jobs run together every 10 minutes.Schedule::describe(5, 10);
// 7 and 60 share no divisor, so the result is their product. This prints 420 minutes.Schedule::describe(7, 60);Every 6 and every 15 minutes: together after 30 minutesEvery 5 and every 10 minutes: together after 10 minutesEvery 7 and every 60 minutes: together after 420 minutes