Trying to find factors of a number in JS

前端 未结 13 2856
陌清茗
陌清茗 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:23

    As an even more performant complement to @the-quodesmith's answer, once you have a factor, you know immediately what its pairing product is:

    function getFactors(num) {
      const isEven = num % 2 === 0;
      let inc = isEven ? 1 : 2;
      let factors = [1, num];
    
      for (let curFactor = isEven ? 2 : 3; Math.pow(curFactor, 2) <= num; curFactor += inc) {
        if (num % curFactor !== 0) continue;
        factors.push(curFactor);
        let compliment = num / curFactor;
        if (compliment !== curFactor) factors.push(compliment);
      }
    
      return factors;
    }
    

    for getFactors(300) this will run the loop only 15 times, as opposed to +-150 for the original.

提交回复
热议问题