There is a task to decompose the numbers from a to b into divisors. These dividers need to be written into an array, which will be part of another array. This code just adds a bunch of divisors of different numbers. I also need the divisors of each number to be in a separate array so that you can work with them further.

function devide(x) { for (let a = 1; a <= x; a++) { if (x % a == 0) { divisors.push([a]) } } } 

Please tell me how to fix it. Thank you in advance!

    1 answer 1

     function getDivisorsRange(a, b) { if (a > b) { var temp = a; a = b; b = temp; } result = new Array(); var index = 0; for (let i = a; i <= b; i++) { result.push({ num: i, divisors: new Array(), }) for (let j = 1; j <= i; j++) { if (i % j == 0) { result[index].divisors.push(j); } } index++; } return result; } getDivisorsRange(25, 40); 

    And further. It is better to slightly optimize the search function of divisors, namely, to make the cycle not up to the number itself, but to the root and, when finding the divisor, insert into the array divisors not only the number itself, but also the number that is not enough to get the number for which we are looking for a divider (unless it is the square root of this number)

    PS something like this:

      for (let j = 1; j <= forto; j++) { if (i % j == 0) { result[index].divisors.push(j); if (j * j != i) { result[index].divisors.push(i / j); } } } 
    • Cool way. Thank! - Edymov