Check for a self-dividing number in JavaScript

A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is self-dividing because it's divisible by 1, 2, and 8. However, any number containing 0 cannot be self-dividing since division by zero is undefined.

What Makes a Number Self-Dividing?

A number qualifies as self-dividing if:

  • It contains no zeros (since division by zero is impossible)
  • The number is evenly divisible by each of its individual digits

Examples

  • 128: Self-dividing because 128 ÷ 1 = 128, 128 ÷ 2 = 64, 128 ÷ 8 = 16
  • 102: Not self-dividing because it contains 0
  • 26: Not self-dividing because 26 ÷ 6 = 4.33... (not evenly divisible)

Implementation

Here's a JavaScript function to check if a number is self-dividing:

const selfDivisible = num => {
    let original = num;
    
    while (num > 0) {
        let digit = num % 10;
        
        // Check if digit is 0 or if original number is not divisible by digit
        if (digit === 0 || original % digit !== 0) {
            return false;
        }
        
        num = Math.floor(num / 10);
    }
    
    return true;
};

// Test cases
const num1 = 128;
const num2 = 102;
const num3 = 26;
const num4 = 36;

console.log(`${num1} is self-dividing:`, selfDivisible(num1));
console.log(`${num2} is self-dividing:`, selfDivisible(num2));
console.log(`${num3} is self-dividing:`, selfDivisible(num3));
console.log(`${num4} is self-dividing:`, selfDivisible(num4));
128 is self-dividing: true
102 is self-dividing: false
26 is self-dividing: false
36 is self-dividing: true

How It Works

The algorithm extracts each digit using the modulo operator (%) and integer division:

  1. Extract the rightmost digit using num % 10
  2. Check if the digit is 0 or if the original number isn't divisible by it
  3. Remove the rightmost digit using Math.floor(num / 10)
  4. Repeat until all digits are processed

Alternative String-Based Approach

You can also solve this by converting the number to a string:

const selfDivisibleString = num => {
    const digits = num.toString().split('');
    
    for (let digit of digits) {
        const digitValue = parseInt(digit);
        if (digitValue === 0 || num % digitValue !== 0) {
            return false;
        }
    }
    
    return true;
};

console.log("Using string method:");
console.log("128:", selfDivisibleString(128));
console.log("102:", selfDivisibleString(102));
Using string method:
128: true
102: false

Conclusion

Self-dividing numbers are those divisible by all their digits, excluding any number containing zero. The mathematical approach using modulo and division is more efficient than string conversion for this problem.

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

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements