We're a place where coders share, stay up-to-date and grow their careers.
Here is my simple solution to finish this problem with PHP:
function decomp($n) { $result = []; $index = 2; for($index=2; $index <= $n; $index++) { $number = $index; $numberIndex = 2; if (isPrime($number) === false) { while (isPrime($number) === false) { if ($number % $numberIndex === 0) { if (array_key_exists((string)$numberIndex, $result) === true) { $result[(string)$numberIndex] += 1; } else { $result[(string)$numberIndex] = 1; } $number = (int)($number / $numberIndex); } else { $numberIndex += 1; } } if (array_key_exists((string)$number, $result)) { $result[(string)$number] += 1; } else { $result[(string)$number] = 1; } } if (isPrime($index) === true) { if (array_key_exists((string)$index, $result)) { $result[(string)$index] += 1; } else { $result[(string)$index] = 1; } } } $answer = ""; foreach($result as $key => $value) { if ($key === 1) { continue; } if($value === 1) { $answer .= $key . " * "; continue; } $answer .= $key . "^" . $value . " * "; } return substr($answer, 0, -3); } function isPrime($n) { $count = ceil(sqrt($n)); for($index=2; $index<=$count; $index++) { if ($n % $index === 0) { return false; } } return true; }
Here is my simple solution to finish this problem with PHP: