Check if all digits of a number divide it in Python

Suppose we have a number n. We have to check whether all digits of it can divide n or not.

So, if the input is like n = 135, then the output will be True, because (135 / 1 = 135), (135 / 3 = 45) and (135 / 5 = 27).

Algorithm

To solve this, we will follow these steps ?

  • val := n
  • while val > 0, do
    • d := val mod 10
    • if n is not divisible by d, then
      • return False
    • val := quotient of (val / 10)
  • return True

Example

Let us see the following implementation to get better understanding ?

def is_divisible(n, d):
    return d != 0 and n % d == 0

def solve(n):
    val = n
    while val > 0:
        d = val % 10
        if not is_divisible(n, d):
            return False
        val = val // 10
    return True

n = 135
print(solve(n))

The output of the above code is ?

True

How It Works

The algorithm extracts each digit from right to left using modulo 10 operation. For each digit, it checks if the original number is divisible by that digit. The helper function is_divisible() ensures we don't divide by zero and checks divisibility using the modulo operator.

Testing with Different Numbers

def is_divisible(n, d):
    return d != 0 and n % d == 0

def solve(n):
    val = n
    while val > 0:
        d = val % 10
        if not is_divisible(n, d):
            return False
        val = val // 10
    return True

# Test different numbers
test_numbers = [135, 111, 120, 144]

for num in test_numbers:
    result = solve(num)
    print(f"{num}: {result}")
135: True
111: True
120: False
144: True

Key Points

  • The function returns False immediately if any digit cannot divide the number
  • Zero digits are handled by checking d != 0 to avoid division by zero
  • The algorithm uses integer division // to remove the last digit in each iteration

Conclusion

This solution efficiently checks if all digits of a number divide the number itself. The algorithm has O(log n) time complexity as it processes each digit once, making it suitable for numbers of any reasonable size.

Updated on: 2026-03-25T14:13:20+05:30

763 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements