Project Euler 007 – JavaScript

18 03 2011

Problem 7

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

Solution

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<!–

By listing the first six prime numbers:

2, 3, 5, 7, 11, and 13, we can see that

the 6th prime is 13.

What is the 10001st prime number?

–>

<title>Project Euler 007</title>

<body>

<script type="text/javascript">

maxPrime = 10001;

primes = new Array(maxPrime);

primes[0] = 2;

primes[1] = 3;

primeCount = 2;

while (primeCount < maxPrime) {

isPrime = false;

candidate = primes[primeCount – 1] + 2;

while (!isPrime) {

isPrime = true;

for (pindex = 0; pindex < primeCount; pindex++) {

prime = primes[pindex];

if (candidate % prime == 0) {

isPrime = false;

break;

}

}

if (!isPrime) { candidate += 2; }

else {

primes[primeCount] = candidate;

primeCount++;

}

}

}

document.write("<b>" + primes[maxPrime-1] + "</b>");

</script>

</body>

</html>

Discussion

Happy JavaScript nth prime finder.