Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I began programming recently. I am trying to implement a simple trial-division algorithm for finding all primes up to some number (it is much more "primitive" algorithm than the Sieve of Eratosthenes). Can you please find what's wrong with my code?

#range function:

range = function (a,b,c){
    var range1=[]
    for (i=a; i<b; i=i+c){
        range1.push(i);
    }
    return range1;
}

#The algorithm:

n=prompt("n");
var numbers=range(2,n,1);
var primes=[];
for (number in numbers){
 var sublist=range(2,number,1);
 console.log(sublist);
 for (x in sublist){
  if (number%x ===0){
   break;
  }
 primes.push(number); 
 }
}

Thanks in advance!

share|improve this question
1  
Is this code working? I'm a little confused at the request "Can you please find what's wrong with my code?" – Jeff Vanzella Sep 18 '12 at 23:26

1 Answer 1

Try using this instead.

// `isPrime` adopted from http://www.javascripter.net/faq/numberisprime.htm
var isPrime = function (n) {
    if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) {
        return false;
    }
    if (n % 2 === 0){
        return (n === 2);
    }
    if (n % 3 === 0){
        return (n === 3);
    }
    for (var i = 5, m = Math.sqrt(n); i <= m; i += 6) {
        if ((n % i === 0) || (n % (i + 2) === 0)){
            return false;
        }
    }
    return true;
}
var getPrimesUntilN = function (n) {
    n = Math.abs(n);
    var primes = (1 < n) ? [2] : [];
    if (isNaN(n) || !isFinite(n)) {
        return primes;
    }
    for (var i = 3; i <= n; i+=2) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    return primes;
};

Input:

getPrimesUntilN(50);

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

share|improve this answer
    
Thank you for your answer. – shauli Sep 1 '12 at 17:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.