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?

–>

<head>

    <title>Project Euler 007</title>

</head>

<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.

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: