Created
November 14, 2023 14:29
-
-
Save ttsuki/0e46d4644d2c7ba7d3891962a6f4197c to your computer and use it in GitHub Desktop.
array_gcd, array_lcm (PHP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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