ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

## to Nth Prime in the PHP Track

Published at Jul 30 2019 · 0 comments
Instructions
Test suite
Solution

#### Note:

This exercise has changed since this solution was written.

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.

## 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 nth-prime/nth-prime_test.php
``````

## Source

A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7

## Submitting Incomplete Solutions

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

### nth-prime_test.php

``````<?php

class NthPrimeTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass() : void
{
require 'nth-prime.php';
}

public function testFirstPrime()
{
\$this->assertEquals(2, prime(1));
}
public function testSecondPrime()
{
\$this->assertEquals(3, prime(2));
}
public function testSixthPrime()
{
\$this->assertEquals(13, prime(6));
}
public function testBigPrime()
{
\$this->assertEquals(104743, prime(10001));
}
public function testZeroPrime()
{
\$this->assertEquals(false, prime(0));
}
}``````
``````<?php

function prime(int \$nth){
if (\$nth === 0){
return false;
}
if (\$nth === 1){
return 2;
}
\$previousPrime = prime(\$nth - 1);
\$currentNum = \$previousPrime+1;
while (!isPrime(\$currentNum)) {
\$currentNum++;
}
return \$currentNum;
}

function isPrime(int \$num){
for (\$i = 2;\$i<\$num/2+1;\$i++){
if (\$num % \$i ===0){
return false;
}
}
return true;
}

echo prime(99);``````