Given a number n, determine what the nth prime is.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them 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 nth-prime/nth-prime_test.php
A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
<?php
class NthPrimeTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass() : void
{
require_once 'nth-prime.php';
}
public function testFirstPrime() : void
{
$this->assertEquals(2, prime(1));
}
public function testSecondPrime() : void
{
$this->assertEquals(3, prime(2));
}
public function testSixthPrime() : void
{
$this->assertEquals(13, prime(6));
}
public function testBigPrime() : void
{
$this->assertEquals(104743, prime(10001));
}
public function testZeroPrime() : void
{
$this->assertEquals(false, prime(0));
}
}
<?php
function is_prime($num) : bool
{
$half = $num / 2;
for ($i = 3; $i < $half; $i += 2) {
if ($num % $i == 0)
return False;
}
return True;
}
function prime($n): int
{
$i = 3;
$nth = 2;
if ($n == 0)
return 0;
if ($n == 1)
return 2;
while ($nth < $n) {
if (is_prime($i += 2))
$nth++;
}
return $i;
}
A huge amount can be learned 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.
Level up your programming skills with 3,388 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments