Count the divisors of a number

Lee·2022년 8월 1일

Algorithm

목록 보기
62/92
post-thumbnail

❓Count the divisors of a number

Q. Count the number of divisors of a positive integer n.

Random tests go up to n = 500000.

Examples (input --> output)
4 --> 3 (1, 2, 4)
5 --> 2 (1, 5)
12 --> 6 (1, 2, 3, 4, 6, 12)
30 --> 8 (1, 2, 3, 5, 6, 10, 15, 30)

✔ Solution

//#my solution
function getDivisorsCnt(n) {
  // todo
  let result = [];

  for (let i = 1; i <= n; i++) {
    if (n % i == 0) {
      result.push(i);
    }
  }
  return result.length;
}

//other solution
function getDivisorsCnt(n) {
  var div = 0;
  for(var i = 1; i <= n; i++) if(n % i == 0) div++;
  return div;
}
profile
Lee

0개의 댓글