logo

Count the divisors of a number

Count the number of divisors of a positive integer n.


My first code passed the simple and medium tests but failed the large tests. The algorithm is not efficient enough:


                        function getDivisorsCnt(n) {
                            if (n === 0) return 0;
                            let count = 0;
                            for (let i = 1; i <= n; i++) { // Start from 1 and go up to n
                                if (n % i === 0) {
                                    count++;
                                }
                            }
                            return count;
                        }
                        
                    

This is my second piece of code, but this time it also checks if the result is not the square root and, if so, counts it as well. Therefore, it's at least twice as fast:


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


And that's the best solution among all users:


                        function getDivisorsCnt(n) {
                            if (n === 1) return 1;
                            let num = 0;
                            let sqrtN = Math.sqrt(n);
                            for (let i = 1; i <= sqrtN; i++) {
                                if (n % i === 0) {
                                    num += (i === n / i) ? 1 : 2; 
                                }
                            }
                            return num;
                        }                    
                    

New things I learned today: