Trying to find factors of a number in JS

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

    @Moob's answer is correct. You must use a loop. However, you can speed up the process by determining if each number is even or odd. Odd numbers don't need to be checked against every number like evens do. Odd numbers can be checked against every-other number. Also, we don't need to check past half the given number as nothing above half will work. Excluding 0 and starting with 1:

    function calculate(num) {
        
        var half = Math.floor(num / 2), // Ensures a whole number <= num.
            str = '1', // 1 will be a part of every solution.
            i, j;
        
        // Determine our increment value for the loop and starting point.
        num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
        
        for (i; i <= half; i += j) {
            num % i === 0 ? str += ',' + i : false;
        }
    
        str += ',' + num; // Always include the original number.
        console.log(str);
    }
    
    calculate(232);

    http://jsfiddle.net/r8wh715t/

    While I understand in your particular case (calculating 232) computation speed isn't a factor (<-- no pun intended), it could be an issue for larger numbers or multiple calculations. I was working on Project Euler problem #12 where I needed this type of function and computation speed was crucial.

提交回复
热议问题