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 N is divisible by a number which is composed of the digits from the set {A, B} in Python
Given a number n and two digits a and b, we need to check if we can form a number using only digits a and b that divides n. This problem can be solved using recursion by generating all possible combinations of numbers formed using the given digits.
For example, if n = 115, a = 3, b = 2, then the output will be True because 115 is divisible by 23, which is made of digits 2 and 3.
Algorithm Steps
To solve this problem, we will follow these steps −
- Define a helper function
util()that takes parameters: temp (current number being formed), a, b, and n - If temp > n, return False (optimization: no point checking numbers larger than n)
- If n is divisible by temp, return True
- Recursively try adding digit 'a' or 'b' to the current number
- From the main function, start with single-digit numbers 'a' and 'b'
Implementation
def util(temp, a, b, n):
# If current number exceeds n, no need to check further
if temp > n:
return False
# Check if n is divisible by current number
if n % temp == 0:
return True
# Try appending digit 'a' or 'b' to current number
return util(temp * 10 + a, a, b, n) or util(temp * 10 + b, a, b, n)
def solve(n, a, b):
# Start with single digit numbers 'a' and 'b'
return util(a, a, b, n) or util(b, a, b, n)
# Test the solution
n = 115
a = 3
b = 2
result = solve(n, a, b)
print(f"Can {n} be divided by a number formed using digits {a} and {b}? {result}")
Can 115 be divided by a number formed using digits 3 and 2? True
How It Works
The algorithm works by recursively building numbers using digits a and b. For the example above −
- Starting with digit 2: checks 2, 22, 23, 222, 223, 232, 233...
- Starting with digit 3: checks 3, 32, 33, 322, 323, 332, 333...
- When it reaches 23, it finds that 115 % 23 = 0, so returns True
Additional Example
# Test with different values
test_cases = [
(100, 2, 5), # 100 is divisible by 25
(17, 3, 7), # 17 is a prime number
(48, 1, 2), # 48 is divisible by 12
]
for n, a, b in test_cases:
result = solve(n, a, b)
print(f"n={n}, a={a}, b={b} ? {result}")
n=100, a=2, b=5 ? True n=17, a=3, b=7 ? False n=48, a=1, b=2 ? True
Conclusion
This recursive approach efficiently generates all possible numbers formed using digits a and b, checking divisibility at each step. The algorithm stops early when a divisor is found or when the generated number exceeds n.
