nonono
nonono

Reputation: 601

Why does this code run differently in JSBin on repeated runs?

On JSBin, this code returns a different number each time it's run, but it doesn't here as a Stack Snippet:

function prime(num) {
  var primes = [];
  var i = 1;
  
  while (primes.length <= num) {
    if (isPrime(i)) {
      primes.push(i);
    }
    i++;
  }
  
  function isPrime(i) {
    for (var k = 2; k <= Math.sqrt(i); k++) {
      if (i % k === 0) {
        return false;
      }
    }
    return true;
  }
  
  return primes.pop();
  
}

console.log(prime(10001));

Link to JSbin. What shows in the console if you run it repeatedly on JSBin:

enter image description here

Upvotes: 1

Views: 80

Answers (1)

Aruna
Aruna

Reputation: 448

If you look at the chrome console, you can see the below warning. Thats why the loop is disconnected randomly at some stage.

Exiting potential infinite loop at line 6. To disable loop protection: add "// noprotect" to your code

If you add the line // noprotect on top of your code as below and run it in JSBin, its giving the right answer all the time.

// noprotect
function prime(num) {
  var primes = [];
  var i = 1;

  while (primes.length <= num) {
    if (isPrime(i)) {
      primes.push(i);
    }
    i++;
  }

.....

Upvotes: 3

Related Questions