Trying to find number factors in JS

I am just starting out JS and understand the concept of finding a factor. However, this piece of code is what I have. I have a str variable that outputs only the first factor, which is 2. I am trying to add each (int) to str as a list of factors. What is wrong in the code snippet below?

function calculate(num) {
    var str = "";
    var int = 2;
    if (num % int == 0) {
        str = str + int;
        int++;
    } else {
        int++;
    }
    alert(str);
}

calculate(232);
+8
source share
13 answers

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/

An array (number) creates an empty array [number] of places

Array.from (arr, (_, i) => i) fills the empty array with values ​​in accordance with the position [0,1,2,3,4,5,6,7,8,9]

.filter(i =>...) [0,1,2,3,4,5] , % === 0, , .

, Math.floor ( /2) , ( ).

@gengns , keys:

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]
+13

@Moob . . , , , . , evens. . , , . 0 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.
    alert(str);
}

calculate(232);

http://jsfiddle.net/r8wh715t/

( 232), (< - ), . Project Euler problem # 12, , .

+10

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

calculate(232);
Hide result

http://jsfiddle.net/67qmt/

+8

@the-quodesmith answer, , , :

function getFactors(num) {
  const isEven = num % 2 === 0;
  let inc = isEven ? 1 : 2;
  let factors = [1, num];

  for (let curFactor = isEven ? 2 : 3; Math.pow(curFactor, 2) <= num; curFactor += inc) {
    if (num % curFactor !== 0) continue;
    factors.push(curFactor);
    let compliment = num / curFactor;
    if (compliment !== curFactor) factors.push(compliment);
  }

  return factors;
}

getFactors(300) 15 , + -150 .

+8

O(sqrt(N)):

function(A) {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}
+1

O (sqrt (N)). - .

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));

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

+1
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

, , , . 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
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

, , /, .

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.
Hide result

, @Harman

0

, javascript. , 5 = 5 * 4 * 3 * 2 * 1 = 120

0

That gave me 85% on Codility (Crash on the upper limit, over a billion).

Cutting the input in half does not work well with large numbers, since half is still a very large cycle. Therefore, I used the object to track the number and its half value, which means that we can reduce the cycle to one quarter, since we work from both ends at the same time. 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;
}
0
source
function factorialize(num) { 
 if(num === 0)
   return 1; 
 var arr = []; 
 for(var i=1; i<= num; i++){
   arr.push(i);
 } 
 num = arr.reduce(function(preVal, curVal){
   return preVal * curVal;
 });

  return num;
}

factorialize(5);
-1
source

Source: https://habr.com/ru/post/1529670/


All Articles