-3

I need a way to find the 10001th prime number. My code prints out all the prime numbers but I'm not sure how to get the 10001th prime number.

function prime(nth) {
  var arr = [2];
  var isPrime = true;

    for(var i = 3; i <= 100; i++) {
        isPrime = true;
        for(var j = 2; j < i; j++) {
            if(i % j === 0) {
              isPrime = false;
              break;

            }
        }
        if(isPrime === true) {
          arr.push(i);
        }
    }
    return arr;
}
prime();
jyoon006
  • 739
  • 3
  • 9
  • 14
  • well, you stop looking at `100`, so you'll never find the `10,001`th prime... – Marc B May 26 '15 at 20:57
  • Loop until your array has a length of 10001 instead of stopping at i<=100 ? – Denys Séguret May 26 '15 at 20:57
  • 1
    "I copied and pasted some code that does something similar to my homework, but it's not quite right; can someone fix it for me so that I don't have to learn anything?" – Blorgbeard May 26 '15 at 20:58
  • Your code does not print out all the prime numbers; it just finds the primes less than 100 (and not very efficiently). – Pointy May 26 '15 at 20:58
  • I know my loops stops at 100. even if i change to 10001, i only goes up to 10001, and doesnt find the 10001th prime. I need the code to run till array length is 10001 and then I can pop() the last array value out. – jyoon006 May 26 '15 at 20:59
  • Well, do that then. Do you know how to check the length of an array? You just need to change your for-loop to check for that instead of i <= 100/ – Blorgbeard May 26 '15 at 21:04
  • possible duplicate of [Find 10000th prime number](http://stackoverflow.com/questions/26791129/find-10000th-prime-number) –  May 26 '15 at 21:04

1 Answers1

1

Use the length of the prime array as the looping condition of your for loop, not the number you're testing.

function prime(nth) {
    var arr = [2];
    var isPrime = true;

    for(var i = 3; arr.length <= nth; i++) {
        isPrime = true;
        for(var j = 2; j < i; j++) {
            if(i % j === 0) {
                isPrime = false;
                break;

            }
        }
        if(isPrime === true) {
            arr.push(i);
        }
    }
    return arr;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612