0

the functions below are supposed to spit out the nth prime number. However, it keeps on spitting out 3. Can somebody please help? Cheers, Anthony

function Prime(num) {
output = true  
    for (i=2 ; i<num ; i++) {
        if (num%i === 0)  {
           output = false ; break
        }
    }
return output
}

function PrimeMover(num) {
var count = 0
    for (i=2 ; i<10000 ; i++)  {
        if (Prime(i) === true) {
            count = count + 1 
        }
        if (count === num) {
            return i
            break
        } 
    }
}
Anthony
  • 21
  • 1
  • 4
  • You need to use local variables. Otherwise, all of your loops will overwrite each other! Take a look at my prime number programming interface here: http://www.myersdaily.org/joseph/javascript/primes-10k.2.html in which you can do what you want with code like this `var t = [], i=2, n = 300; while (t.length < n) { prime(i) && (t[t.length] = i); i++; } t[t.length-1]; // our list` then just click "Execute" (outputs 1987) – Joseph Myers Mar 17 '15 at 04:54
  • PS typing 10000 into the above code, the 10000th prime is 104729. – Joseph Myers Mar 17 '15 at 04:59
  • 1
    Related questions: [Writing first 100 prime numbers to a file using node.js](http://stackoverflow.com/questions/17382910/writing-first-100-prime-numbers-to-a-file-using-node-js) and [How to find prime numbers between 0 - 100?](http://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100) – jfriend00 Mar 17 '15 at 05:22

7 Answers7

2

You have created loop counter i in global scope.so both PrimeMover and Prime mutates same global i.In every iteration ,PrimeMover assigns i=2.After that Prime assigns i=2.your i variable's value will be changed between 2 and 3.use local loop counter variable var i=0;

function Prime(num) {
output = true  
for (var i=2 ; i<num ; i++) { //var i=2
    if (num%i === 0)  {
       output = false ; break
    }
}
return output
}

function PrimeMover(num) {
var count = 0
for (var i=2 ; i<10000 ; i++)  { //var i=2
    if (Prime(i) === true) {
        count = count + 1 
    }
    if (count === num) {
        return i
        break
    } 
}
}
balajisoundar
  • 581
  • 2
  • 11
  • @ Joseph and Balaji,Understood. Thank you so much. – Anthony Mar 17 '15 at 06:48
  • Instead of using an `output` variable, can you not simply return `false` in the loop and return `true` at the end? I think that would be easier. – Ethan McTague Oct 23 '15 at 12:48
  • Yes , that would be much more readable . But i was trying to explain the bug in the code.Thanks for your comment.:) – balajisoundar Oct 26 '15 at 05:41
  • Also, it is enough to look for dividers from 2 to square root of num. And in your main fn, if i is greather then or equal to 3, you can increase i again (skipp the even numbers)... – ppseprus Jan 05 '16 at 16:40
2

For minimal code lovers,

function nthprime(n)
{
  var prime=[], i=1
  while (i++ && prime.length<n) prime.reduce((a,c)=>(i%c)*a,2) && prime.push(i)
  return prime.length?prime.pop():-1
}
[-1,0,1,2,3,5,10,100].forEach(n=>console.log(`nthprime(${n})=${nthprime(n)}`))
Won
  • 1,795
  • 2
  • 12
  • 22
  • 3
    Nice answer, except that mathematicians exclude 1 from the list, and consider 2 as the smallest prime number (you have `nthprime(1)==1`). – Purplejacket Feb 16 '20 at 00:47
1
function main(inp) {
  var count = 0;
  for (var i = 2; i <= 100000; i++) {
   if (isPrime(i)) count = count + 1;
   if (count == inp) return i;
 }
}
function isPrime(i) {
 for (var j = 2; j < i; j++) {
  //instead of `j < i` it can be reduced using other conditions 
  if (i % j == 0) {
   return false
  }
 }
 return true
}
main(5) // any number
Ashish Yadav
  • 3,039
  • 1
  • 16
  • 23
0

This might be a bit more optimal

function nthPrime(n) {
    var P = 0;

    function isPrime(x) {
        var isPrime= true;

        for (var d = 2; d <= Math.sqrt(x); d++) {
            if((x/d) % 1 == 0) {
                isPrime = false;
                break;
            }
        }

        return isPrime;
    }

    for (var i = 1; 0 < n; i++) {

        if(isPrime(i)) {
            P = i; n--;
        }

        // we can skip the even numbers
        if(3 <= i){
            i++;
        }

    }

    return P;
}
ppseprus
  • 538
  • 1
  • 8
  • 26
0

Try this

var pos=10001;
console.log(primeNumforPos(pos));

function primeNumforPos(pos){
  var num=2,curPos=0;
  while(curPos<=pos){
    if(isPrime(num)){
      curPos++;
    }
    if(curPos==pos){
      return num;
    }else{
      num++;
    }
  }
}

function isPrime(num){
  for(var i=2;i<=Math.sqrt(num);i++){
    if(num%i==0){
      return false;
    }
  }
  return true;
}
  • Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem. – Sven Eberth Jun 06 '21 at 16:10
0

So, I decided to optimise the hell out of the code (cuz why not). It is almost 6 times as fast as that of ppseprus (297ms vs 1773ms in nth_prime(100000)).

let primes = [2, 3]; 

const nth_prime = (n) => {
    if (n <= primes.length) return primes[n - 1]; // handle values which have been cached

    let i = 1; 
    
    while (1){
        const a = 6 * i - 1, b = 6 * i + 1, a_limit = Math.sqrt(a), b_limit = Math.sqrt(b); // the 6n - 1 and 6n + 1 rule for primes
        let a_prime = true, b_prime = true; 

        i++; 
        
        // prime check

        for (const prime of primes){
            if (prime > a_limit) break; 
            if (a % prime == 0){
                a_prime = false; 
                break; 
            }
        }
        
        if (a_prime){
            if (primes.length + 1 == n) return a; 
            primes.push(a); // cache
        }
        
        for (const prime of primes){
            if (prime > b_limit) break; 
            if (b % prime == 0){
                b_prime = false; 
                break; 
            }
        }
        
        if (b_prime){
            if (primes.length + 1 == n) return b; 
            primes.push(b); // cache
        }
    }
}
-1
const findPrime = num => {
let i, primes = [2, 3], n = 5
const isPrime = n => {
    let i = 1, p = primes[i],
        limit = Math.ceil(Math.sqrt(n))
    while (p <= limit) {
        if (n % p === 0) {
            return false
        }
        i += 1
        p = primes[i]
    }
    return true
}
for (i = 2; i <= num; i += 1) {
    while (!isPrime(n)) {
        n += 2
    }
    primes.push(n)
    n += 2
};
return primes[num - 1]

} console.time('Time')

let x = findPrime(9999)

console.timeEnd('Time')

console.log(x)

Saju
  • 1