先对数字进行因式分解算法
再过滤结果集中,不符合的结果集。
class Helper
{
public function chechPrime($num)
{
for ($i = floor(sqrt($num)); $i > 1; --$i) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
public function getFactorNumber(array &$result, array &$list, $n, $startFactor)
{
if ($n == 1) {
if (count($list) > 1) {
$result[] = $list;
}
return;
}
for ($i = $startFactor; $i <= floor(sqrt($n)); ++$i) {
if ($n % $i === 0) {
array_push($list, $i);
$this->getFactorNumber($result, $list, $n / $i, $i);
array_pop($list);
}
}
array_push($list, $n);
$this->getFactorNumber($result, $list, 1, $n);
array_pop($list);
}
public function primeFactorNumber($num): array
{
$result = [];
$list = [];
$this->getFactorNumber($result, $list, $num, 2);
array_push($result, [$num, 1]);
$result = array_filter($result, function ($value) {
foreach ($value as $v) {
if (!$this->chechPrime($v)) {
return false;
}
}
return true;
});
return $result;
}
}
$helper = new Helper();
$result = $helper->primeFactorNumber(90);
var_dump($result);