# 4d47's solution

## to Prime Factors in the PHP Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

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.

## Example

What are the prime factors of 60?

• Our first divisor is 2. 2 goes into 60, leaving 30.
• 2 goes into 30, leaving 15.
• 2 doesn't go cleanly into 15. So let's move on to our next divisor, 3.
• 3 goes cleanly into 15, leaving 5.
• 3 does not go cleanly into 5. The next possible factor is 4.
• 4 does not go cleanly into 5. The next possible factor is 5.
• 5 does go cleanly into 5.
• We're left only with 1, so now, we're done.

Our successful divisors in that computation represent the list of prime factors of 60: 2, 2, 3, and 5.

You can check this yourself:

• 2 * 2 * 3 * 5
• = 4 * 15
• = 60
• Success!

## Running the tests

1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`. To find the Exercism workspace run

`````` % exercism debug | grep Workspace
``````
2. Get PHPUnit if you don't have it already.

`````` % wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
% chmod +x phpunit.phar
``````
3. Execute the tests:

`````` % ./phpunit.phar prime-factors/prime-factors_test.php
``````

## Source

The Prime Factors Kata by Uncle Bob http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### prime-factors_test.php

``````<?php
require_once "prime-factors.php";

class PrimeFactorsTest extends PHPUnit\Framework\TestCase
{
public function testNoFactors()
{
\$this->assertSame([], factors(1));
}

public function testOneFactor()
{
\$this->assertSame([2], factors(2));
}

public function testSquareOfPrime()
{
\$this->assertSame([3, 3], factors(9));
}

public function testCubeOfPrime()
{
\$this->assertSame([2, 2, 2], factors(8));
}

public function testProductOfPrimesAndNon()
{
\$this->assertEquals([2, 2, 3], factors(12));
}

public function testProductOfPrimes()
{
\$this->assertEquals([5, 17, 23, 461], factors(901255));
}

public function testFactorsIncludeLargePrime()
{
\$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;
}``````