Trying to find factors of a number in JS

前端 未结 13 2677
陌清茗
陌清茗 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条回答
  •  旧时难觅i
    2021-02-19 05:39

    Here's an optimized solution using best practices, proper code style/readability, and returns the results in an ordered array.

    function getFactors(num) {
        const maxFactorNum = Math.floor(Math.sqrt(num));
        const factorArr = [];
        let count = 0;  //count of factors found < maxFactorNum.
    
        for (let i = 1; i <= maxFactorNum; i++) {
            //inserting new elements in the middle using splice
            if (num % i === 0) {
                factorArr.splice(count, 0, i);
                let otherFactor = num / i; //the other factor
                if (i != otherFactor) {
                    //insert these factors in the front of the array
                    factorArr.splice(-count, 0, otherFactor);
                }
                count++;
            }
        }
    
        //swapping first and last elements
        let lastIndex = factorArr.length - 1;
        let temp = factorArr[lastIndex];
        factorArr[lastIndex] = factorArr[0];
        factorArr[0] = temp;
    
        return factorArr;
    }
    
    console.log(getFactors(100));
    console.log(getFactors(240));
    console.log(getFactors(600851475143)); //large number used in Project Euler.

    I based my answer on the answer written by @Harman

提交回复
热议问题