TAGS :Viewed: 7 - Published at: a few seconds ago

[ Euler 7 Javascript ]

Can someone help with this code? It's supposed to get the 10,001th prime number. I know the is_prime function works to test if a number is prime since I successfully utilized this code for a previous problem. Now I'm just trying to call that in a for loop until counter hits what I want, while storing the most recent number into a variable 'holder' and printing holder at the end.

function is_prime(num) {
    if (isNaN(num)) return false;
    for (var i=2; i<=Math.sqrt(num); i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}

function getBigPrime () {
var holder = 0;
var counter = 0;
    for (var k=3; counter<=10000; k+=2) {
        if (is_prime(k)) 
            holder = k; 
            counter += 1;
    }
    console.log(holder);
}

getBigPrime();

Answer 1


If you omit the brackets for an if block, only the first line will actually be part of your block. Your current if statement behaves like this:

if (is_prime(k)) {
    holder = k; 
}

counter += 1;

Also, your loop skips 2, the first prime number.

Answer 2


You have a scoping error with counter. For your for loop you can initialize counter = 1; to account for 2 and leave as is

http://jsfiddle.net/XtTYm/2/

function is_prime(num) {
    if (isNaN(num)) return false;
    var sq = Math.sqrt(num);
    for (var i=2; i<=sq; i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}

    function getBigPrime () {
    var holder = 0;
    var counter = 1;
        for (var k=3; counter<=10000; k+=2) { 
            if (is_prime(k)){ 
                holder = k; 
                counter += 1; // should be inside the if
            }
        }
        console.log(holder);
    }

    getBigPrime();