Nth Prime

Find the nth prime number using primality testing.

Code

Algorithms
function isPrime($x) {
    if ($x < 2) return false;
    for ($i = 2; $i * $i <= $x; $i++) {
        if ($x % $i === 0) return false;
    }
    return true;
}
$count = 0; $num = 1;
while ($count < $n) {
    $num++;
    if (isPrime($num)) $count++;
}
$num;

Parameters

Position (1-indexed)

Server

More PHP Snippets