Trying to find factors of a number in JS

前端 未结 13 2801
陌清茗
陌清茗 2021-02-19 04:52

I am just starting JS, and understand the concept of finding a factor. However, this snippet of code is what I have so far. I have the str variable that outputs nothing but the

13条回答
  •  不思量自难忘°
    2021-02-19 05:29

    Below is an implementation with the time complexity O(sqrt(N)):

    function(A) {
      var output = [];
    
      for (var i=1; i <= Math.sqrt(A); i++) {
        if (A % i === 0) {
          output.push(i);
    
          if (i !== Math.sqrt(A)) output.push(A/i);
        }
      }
    
      if (output.indexOf(A) === -1) output.push(A);
    
      return output;
    }
    

提交回复
热议问题