Write a PHP web service, factors.php, which will return
(in text/plain
) the prime factors of a
provided number. For example, the request factors.php?n=264
would return:
2 * 2 * 2 * 3 * 11
You can make queries to the working solution to test.
One simple algorithm for prime factorization of num
is as follows:
for fact from 2 to num: while num % fact = 0: num = num / fact add fact to the list of prime factors of the original num
Make your web service return a 400 Invalid Request
HTTP error code with
an instructive error message if the parameter n
is not provided.
<?php header('Content-type: text/plain'); if (!isset($_GET['n'])) { header('HTTP/1.1 400 Invalid Request'); print "Please provide a parameter n."; } else { $factors = factorize($_GET["n"]); print implode(" * ", $factors); } function factorize($num) { $factors = array(); for ($factor = 2; $factor <= $num; $factor++) { while ($num % $factor == 0) { $num /= $factor; array_push($factors, $factor); } } return $factors; } ?>