PHP Common Prime Divisors
function commonPrimeDivisors(array $a, array $b): int
{
$gcd = static function (int $n, int $m) use (&$gcd) {
if ($n % $m === 0) {
return $m;
}
return $gcd($m, $n % $m);
};
$removeCommonPrimeDivisors = static function (int $n, int $m) use ($gcd) {
while ($n !== 1) {
$d = $gcd($n, $m);
if ($d === 1) {
break;
}
$n /= $d;
}
return $n;
};
$counter = 0;
for ($i = 0, $count = count($a); $i < $count; $i++) {
$x = $a[$i];
$y = $b[$i];
$d = $gcd($x, $y);
$x = $removeCommonPrimeDivisors($x, $d);
if ($x !== 1) {
continue;
}
$y = $removeCommonPrimeDivisors($y, $d);
if ($y === 1) {
$counter++;
}
}
return $counter;
}
This checks whether two numbers are built from the same prime factors by repeatedly dividing out their shared parts.