Tell me more ×
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

2 Answers

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
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 (y=0; y<numbers.length;y++)
{
  var sublist=range(2,numbers[y],1), isPrime = true;

  for (x=0; x<sublist.length;x++)
  {
   if (numbers[y] % sublist[x] === 0)
   {
     isPrime = false;
     break;
   }
 }
 if(isPrime)
 {
     primes.push(numbers[y]); 
 }
}
console.log(primes);
share|improve this answer
This algorithm return all odd-numbers up to n, rather than all primes up to n. – shauli Sep 1 '12 at 17:22
@shauli, you are right, I fixed it. – Maciej Sep 4 '12 at 21:25
@Maciej it is usually better if you put a brief english explanation with your answer. – Jeff Vanzella Sep 24 '12 at 2:56

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.