본문 바로가기
알고리즘/Codewars

[Codewars] Count the divisors of a number (7 kyu) / JavaScript

by fluss 2023. 4. 28.

https://www.codewars.com/kata/542c0f198e077084c0000c2e

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Count the number of divisors of a positive integer n.

Random tests go up to n = 500000.

 

Examples (input --> output)

4 --> 3 // we have 3 divisors - 1, 2 and 4
5 --> 2 // we have 2 divisors - 1 and 5
12 --> 6 // we have 6 divisors - 1, 2, 3, 4, 6 and 12
30 --> 8 // we have 8 divisors - 1, 2, 3, 5, 6, 10, 15 and 30

Note you should only return a number, the count of divisors. The numbers between parentheses are shown only for you to see which numbers are counted in each case.

 

코드

function getDivisorsCnt(n){
  let count = 0;
  for(let i = 1; i * i <= n; i++){
    if(n % i === 0) count += 2;
    if(i * i === n) count--;
  }
  return count;
}

댓글