- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting divisors of a number using JavaScript
Problem
We are required to write a JavaScript function that takes in a number and returns the count of its divisor.
Input
const num = 30;
Output
const output = 8;
Because the divisors are −
1, 2, 3, 5, 6, 10, 15, 30
Example
Following is the code −
const num = 30; const countDivisors = (num = 1) => { if (num === 1) return num let divArr = [[2, 0]] let div = divArr[0][0] while (num > 1) { if (num % div === 0) { for (let i = 0; divArr.length; i++) { if (divArr[i][0] === div) { divArr[i][1] += 1 break } else { if (i === divArr.length - 1) { divArr.push([div, 1]) break } } } num /= div } else { div += 1 } } for (let i = 0; i < divArr.length; i++) { num *= divArr[i][1] + 1 } return num } console.log(countDivisors(num));
Output
8
Advertisements
To Continue Learning Please Login
Login with Google