Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Need feedback for prime mover in javascript
    Hi, guys. While I'm solving issue "prime mover", I've got this code:
    function PrimeMover(num) { 
      var r = [2];
      var i = 3;
    
      while(r.length < num) {
        if((function(l) {    
          for(j=1; j<l; j++)
            if(i % r[j] == 0)
              return false;
          return true;
          })(r.length)) r.push(i);
        i+=2;
      }
    
      return r[r.length - 1];
    }
    
    PrimeMover(readline());
    
    Can you tell me about this code? Does this ok? Work fine, but is it normal style?
    Dimko posted this question on 1/7/14 | prime, javascript
    Answers
  • +
  • 3
  • -
  • It doesn't look like normal style to me. I don't like the idea that you have a function declaration inside of a loop. That means that every loop. I would suggest moving the function above the loop, or out of the PrimeMover function. The only other thing that I can think of to suggest is to use descriptive variables. Single letter variables (outside of the index for a for loop) drive me crazy.
    function PrimeMover(num) { 
      var r = [2];
      var i = 3;
    
      while(r.length < num) {
        if(r.length) {
            r.push(i);
            i+=2;
      }
    
      return r[r.length - 1];
    }
    
    function(l) {    
          for(j=1; j<l; j++)
            if(i % r[j] == 0)
              return false;
          return true;
          }
    
    Log in to write an answer.