Trying to find factors of a number in JS

前端 未结 13 2859
陌清茗
陌清茗 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
    function factorialize(num) {
     var result = '';
      if( num === 0){
        return 1;
      }else{
        var myNum = [];
    
      for(i = 1; i <= num; i++){
        myNum.push(i);
        result = myNum.reduce(function(pre,cur){
          return pre * cur;
        });
      }
         return result;
        }
    }
    
    factorialize(9);
    
    0 讨论(0)
  • 2021-02-19 05:37

    I came looking for an algorithm for this for use in factoring quadratic equations, meaning I need to consider both positive and negative numbers and factors. The below function does that and returns a list of factor pairs. Fiddle.

    function getFactors(n) {
      if (n === 0) {return "∞";} // Deal with 0
      if (n % 1 !== 0) {return "The input must be an integer.";} // Deal with non-integers
    
      // Check only up to the square root of the absolute value of n
      // All factors above that will pair with factors below that
      var absval_of_n = Math.abs(n),
          sqrt_of_n = Math.sqrt(absval_of_n),
          numbers_to_check = [];
      for (var i=1; i <= sqrt_of_n; i++) {
        numbers_to_check.push(i);
      }
    
      // Create an array of factor pairs
      var factors = [];
      for (var i=0; i <= numbers_to_check.length; i++) {
        if (absval_of_n % i === 0) {
          // Include both positive and negative factors
          if (n>0) {
            factors.push([i, absval_of_n/i]);
            factors.push([-i, -absval_of_n/i]);
          } else {
            factors.push([-i, absval_of_n/i]);
            factors.push([i, -absval_of_n/i]);
          }
        }
      }
    
      // Test for the console
      console.log("FACTORS OF "+n+":\n"+
                  "There are "+factors.length+" factor pairs.");
      for (var i=0; i<factors.length; i++) {
        console.log(factors[i]);
      }
    
      return factors;
    }
    
    getFactors(-26);
    
    0 讨论(0)
  • 2021-02-19 05:38
    function calculate(num){
        var str = "0"   // initializes a place holder for var str
          for(i=2;i<num;i++){     
            var num2 = num%i;
            if(num2 ==0){       
                str = str +i; // this line joins the factors to the var str
            }
        }
        str1 = str.substr(1) //This removes the initial --var str = "0" at line 2
        console.log(str1) 
    }
    calculate(232);
    
    //Output 2482958116
    
    0 讨论(0)
  • 2021-02-19 05:39

    UPDATED ES6 version:

    As @gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method:

    const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0);
    console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

    ES6 version:

    const factors = number => Array
        .from(Array(number + 1), (_, i) => i)
        .filter(i => number % i === 0)
    
    console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

    https://jsfiddle.net/1bkpq17b/

    • Array(number) creates an empty array of [number] places

    • Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9]

    • .filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number.

    Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small).

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-19 05:42

    function calculate(num) {
        var str = "0";
        for (var i = 1; i <= num; i++) {
            if (num % i == 0) {
                str += ',' + i;
            }
        }
        alert(str);
    }
    
    calculate(232);

    http://jsfiddle.net/67qmt/

    0 讨论(0)
提交回复
热议问题