3
\$\begingroup\$

I am trying to sort all the divisors of a given number in the most efficient way.

Below is my code for sorting the divisors:

num = 100;
end = num ** (1 / 2);
divisors = [1];
disvisorPairs = [];
pairCount = 0;
for (var i = 2; i <= end; i++) {
  if (num % i == 0) {
    divisors.push(i);
    pair = num / i;
    if (pair != i) {
      pairCount++;
      disvisorPairs.push(pair);
    }
  }
}
for (var i = pairCount - 1; i >= 0; i--) {
  divisors.push(disvisorPairs[i]);
}
if (num != 1) divisors.push(num);
console.log(divisors);

  • Is there anything else I can do to increase the performance of my code?
  • Is there a data structure other than arrays that can possibly sort the the divisors in constant time?
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

There are a couple of optimisations you can make to your code:

  1. Rather than initialise divisors to [1], and then dealing with the special case of num != 1 at the end, just initialise divisors to an empty array and loop from 1 to end instead of 2. Your if (pair != i) test will prevent 1 being pushed into the divisorPairs array.
  2. Instead of pushing values onto the end of divisorPairs, use unshift to add them to the beginning of the array instead. Then you can simply concat divisors and divisorPairs after the loop

num = 100;
end = num ** (1 / 2);
divisors = [];
divisorPairs = [];
for (var i = 1; i <= end; i++) {
  if (num % i == 0) {
    divisors.push(i);
    pair = num / i;
    if (pair != i) {
      divisorPairs.unshift(pair);
    }
  }
}
divisors = divisors.concat(divisorPairs);
console.log(divisors);

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.