Number of digits that divide the complete number in JavaScript

We are required to write a JavaScript function that takes in a number as the first and the only argument. The function should count and return the number of digits present in the number that completely divide the number.

For example, if the input number is 148, the output should be 2 because 148 is exactly divisible by 1 and 4 but not 8.

Example Input and Output

Input: 148
Output: 2

This is because:

  • 148 ÷ 1 = 148 (divisible)
  • 148 ÷ 4 = 37 (divisible)
  • 148 ÷ 8 = 18.5 (not divisible)

Implementation

The solution converts the number to a string to extract individual digits, then checks if each digit divides the original number evenly:

const num = 148;
const countDividingDigits = (num = 1) => {
    let count = 0;
    const numStr = String(num);
    for(let i = 0; i < numStr.length; i++){
        const curr = +numStr[i];
        if(num % curr === 0){
            count++;
        };
    };
    return count;
};
console.log(countDividingDigits(num));
2

How It Works

The function follows these steps:

  1. Convert the number to a string to access individual digits
  2. Loop through each character in the string
  3. Convert each character back to a number using the unary plus operator (+)
  4. Check if the original number is divisible by the current digit using the modulo operator (%)
  5. If divisible (remainder is 0), increment the counter
  6. Return the final count

Additional Examples

// Test with different numbers
console.log(countDividingDigits(123));  // 1 is divisor, 2 and 3 are not
console.log(countDividingDigits(111));  // All three 1's are divisors
console.log(countDividingDigits(246));  // 2, 4, and 6 all divide 246
1
3
3

Edge Cases

Note that this function doesn't handle division by zero. If the number contains a 0 digit, the modulo operation would cause an error or unexpected behavior in some cases.

Conclusion

This solution efficiently counts divisible digits by converting the number to a string for digit extraction and using the modulo operator to check divisibility. The time complexity is O(d) where d is the number of digits.

Updated on: 2026-03-15T23:19:00+05:30

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements