Compute the prime factors of a given natural number.
A prime number is only evenly divisible by itself and 1.
Note that 1 is not a prime number.
What are the prime factors of 60?
Our successful divisors in that computation represent the list of prime factors of 60: 2, 2, 3, and 5.
You can check this yourself:
Go to the root of your PHP exercise directory, which is <EXERCISM_WORKSPACE>/php
.
To find the Exercism workspace run
% exercism debug | grep Workspace
Get PHPUnit if you don't have it already.
% wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
% chmod +x phpunit.phar
Execute the tests:
% ./phpunit.phar prime-factors/prime-factors_test.php
The Prime Factors Kata by Uncle Bob http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
<?php
require_once "prime-factors.php";
class PrimeFactorsTest extends PHPUnit\Framework\TestCase
{
public function testNoFactors()
{
$this->assertSame([], factors(1));
}
public function testOneFactor()
{
$this->markTestSkipped();
$this->assertSame([2], factors(2));
}
public function testSquareOfPrime()
{
$this->markTestSkipped();
$this->assertSame([3, 3], factors(9));
}
public function testCubeOfPrime()
{
$this->markTestSkipped();
$this->assertSame([2, 2, 2], factors(8));
}
public function testProductOfPrimesAndNon()
{
$this->markTestSkipped();
$this->assertEquals([2, 2, 3], factors(12));
}
public function testProductOfPrimes()
{
$this->markTestSkipped();
$this->assertEquals([5, 17, 23, 461], factors(901255));
}
public function testFactorsIncludeLargePrime()
{
$this->markTestSkipped();
$this->assertEquals([11, 9539, 894119], factors(93819012551));
}
}
<?php
function factors($n) {
$factors = [];
$n = gmp_init("$n");
for ($i = gmp_init(2); gmp_cmp($i, gmp_div($n, $i)) <= 0; $i = gmp_add($i, 1)) {
while (gmp_mod($n, $i) == 0) {
$factors[] = gmp_intval($i);
$n = gmp_div($n, $i);
}
}
if (gmp_cmp($n, 1) == 1) {
$factors[] = gmp_intval($n);
}
return $factors;
}
A huge amount can be learnt from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Community comments
Using GMP to nail down last test. Still don't have full understanding why default arithmetic and bcmath failed.