Two functions for the same thing, one crashes and the other does not, why?
<p>I want a function called findFirst that takes parameters n and q and returns the smallest prime number dividing n that is greater than or equal to q. So first I wrote a function that would say if a number is prime or not.</p>

<pre><code>var isPrime = function(n){
    if(n === 1){
        return false;
    }
    else if (n === 2 || n === 3){
        return true;
    }
    else {
        for(i=2; i &lt; n; i++){
            if(i * i &gt;= n){
            for(j=2; j&lt;=i; j++){
                    if(n % j === 0){
                        return false;
                    }
                }
            return true;
            } 
        }
    }
};
</code></pre>

<p>There could be other ways to make this more efficient, but I am pretty sure this function is not the problem.</p>

<p>So with this function I made my first attempt to write findFirst:</p>

<pre><code>var findFirst = function(n,q){
    var p = q;
        while(n % p !== 0 || isPrime(p) === false){
            p++;
        }
    return p;
};
</code></pre>

<p>This function works, but with large numbers it crashes, for example it crashes on input (6310545154, 3). By the way the prime power decomposition of 6310545154 is 2 * 3155272577</p>

<p>So I wrote another function that would first just list the prime factors of a number:</p>

<pre><code>var getFactors = function(n){
    var factors = [];
    var k = n;
    var p = 2;
    while(isPrime(k) === false &amp;&amp; k !== 1){
        while(k % p !== 0 || isPrime(p) === false){
            p = p+1;
        }
        while(k % p === 0){
            k = k/p;
        }
        factors.push(p);
    }
    if(isPrime(k) === true){
        factors.push(k);
        return factors;
    }
    if(k === 1){
        return factors; 
    }
};
</code></pre>

<p>And now my second attempt at findFirst is:</p>

<pre><code>var findFirst = function(n,q){
    var array = getFactors(n);
    var p = 0;
    for(i = 0; i &lt; array.length; i++){
        if(array[i] &gt;= q &amp;&amp; p === 0){
            p = array[i];
        }
    }
    return p;
};
</code></pre>

<p>This one works great. It doesn't crash on that large number above and computes the result instantly. Can anyone see why this would happen? It seems like the 'while' loop in my original attempt is pretty similar to one of the 'while' loops in the getFactors function. And the second attempt looks a lot more complicated.</p>
