问题
I am trying to find the 10,001th prime number. I have looked at other code people have written , but I don't really understand what it means. I have written some code in JavaScript in which I tried to use the Sieve Of Eratosthenes. I'm not sure what the problem is. It looks as if it should work correctly, but I'm getting the wrong answer.
var compute = function() {
var prime = [2,3,5,7,11,13,17,19];
for(var i=20; i<=80000;i++) {
if(i%2!==0 && i%3!==0 && i%5!==0 && i%7!==0 && i%11!==0 && i%13!==0 && i%17!==0 && i%19!==0) {
prime.push(i);
}
}
console.log(prime[10000]);
};
compute();
回答1:
This is a simple method, but to find the millionth
(or even hundred thousandth in some machines)
you'll need to chop it up with timeouts,
or ship it off to a webworker to keep from locking up.
You only need to check the prime divisors, as you collect them,
since every number is either the product of primes
or is itself prime.
function nthPrime(nth){
var P= [2], n= 3, div, i, limit,isPrime;
while(P.length<nth){
div= 3, i= 1;
limit= Math.sqrt(n)+1;
isPrime= true;
while(div<limit){
if(n%div=== 0){
isPrime= false;
div= limit;
}
else div= P[i++] || div+ 2;
}
if(isPrime) P.push(n);
n+= 2;
}
return P[P.length-1];
}
alert(nthPrime(10001));
回答2:
Your code does not implement the sieve of Eratosthenes. You have to implement the following steps (source: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes):
- Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
- Initially, let p equal 2, the first prime number.
- Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
- Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
If you want to find the 10001st prime number, you have to choose n large enough, so that the resulting array includes at least 10001 elements, then choose the 10001st element as result.
来源:https://stackoverflow.com/questions/16074244/finding-the-10001st-prime-number-project-euler