Skip to content

Instantly share code, notes, and snippets.

@ttsuki
Created November 14, 2023 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttsuki/0e46d4644d2c7ba7d3891962a6f4197c to your computer and use it in GitHub Desktop.
Save ttsuki/0e46d4644d2c7ba7d3891962a6f4197c to your computer and use it in GitHub Desktop.
array_gcd, array_lcm (PHP)
<?php
function array_gcd(array $arr): int
{
return array_reduce($arr, function (int $a, int $b): int {
while ($b) {
$r = $a % $b;
$a = $b;
$b = $r;
}
return $a;
}, $arr[0]);
}
function array_lcm(array $arr): int
{
return array_reduce($arr, function (int $a, int $b): int {
return $a / array_gcd([$a, $b]) * $b;
}, 1);
}
echo array_lcm(range(1, 6)); // outputs 60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment