Trying to find factors of a number in JS

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

    here is a performance friendly version with complexity O(sqrt(N)). Output is a sorted array without using sort.

    var factors = (num) => {
    let fac = [], i = 1, ind = 0;
    
    while (i <= Math.floor(Math.sqrt(num))) {
      //inserting new elements in the middle using splice
      if (num%i === 0) {
        fac.splice(ind,0,i);
        if (i != num/i) {
          fac.splice(-ind,0,num/i);
        }
        ind++;
      }
      i++;
    }
    
    //swapping first and last elements
    let temp = fac[fac.length - 1];
    fac[fac.length - 1] = fac[0];
    fac[0] = temp;
    
    // nice sorted array of factors
    return fac;
    };
    console.log(factors(100));
    

    Output: [ 1, 2, 4, 5, 10, 20, 25, 50, 100 ]

提交回复
热议问题