Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
Falseimmediately if any digit cannot divide the number - Zero digits are handled by checking
d != 0to 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.
