Trying to find factors of a number in JS

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

    This got me an 85% on Codility (Fails on the upperlimit, over a billion).

    Reducing the input by half doesn't work well on large numbers as half is still a very large loop. So I used an object to keep track of the number and it's half value, meaning that we can reduce the loop to one quarter as we work from both ends simultaneously. N=24 becomes: (1&24),(2&12),(3&8),(4&6)

    function solution(N) {
    
        const factors = {};
    
         let num = 1;  
         let finished = false;
         while(!finished)
         {
             if(factors[num] !== undefined)
             {
                 finished = true;
             }
             else if(Number.isInteger(N/num))
             {
    
              factors[num] = 0;
              factors[N/num]= 0;
             }
            num++
         }
    
        return Object.keys(factors).length;
    }
    

提交回复
热议问题