Find the minimum positive integer such that it is divisible by A and sum of its digits is equal to B in Python

Given two numbers A and B, we need to find the minimum positive integer M such that M is divisible by A and the sum of its digits equals B. If no such number exists, return -1.

For example, if A = 50 and B = 2, the output will be 200 because 200 is divisible by 50 and the sum of its digits (2 + 0 + 0 = 2) equals B.

Approach

We'll use a breadth-first search (BFS) approach with the following strategy ?

  • Use a queue to explore numbers digit by digit

  • Track the remainder when divided by A and current digit sum

  • Use memoization to avoid revisiting the same state

  • Build the number as a string to handle large values

Algorithm Steps

  • Create an Element class to store remainder, current sum, and number string

  • Initialize queue with element (0, 0, "")

  • Mark visited states to avoid cycles

  • For each element, try appending digits 0-9

  • If remainder is 0 and digit sum equals B, return the number

  • Continue until queue is empty or solution found

Implementation

class Element:
    def __init__(self, remainder, digit_sum, number_string):
        self.remainder = remainder
        self.digit_sum = digit_sum
        self.number_string = number_string

def find_minimum_number(A, B):
    # Visited array to track (remainder, digit_sum) states
    visited = [[False for _ in range(B + 1)] for _ in range(A)]
    
    queue = []
    initial_elem = Element(0, 0, "")
    visited[0][0] = True
    queue.append(initial_elem)
    
    while queue:
        current = queue.pop(0)
        
        # If remainder is 0 and digit sum equals B, we found the answer
        if current.remainder == 0 and current.digit_sum == B and current.number_string:
            return int(current.number_string)
        
        # Try appending each digit (0-9)
        for digit in range(10):
            new_remainder = (current.remainder * 10 + digit) % A
            new_sum = current.digit_sum + digit
            
            # Skip if sum exceeds B or state already visited
            if new_sum <= B and not visited[new_remainder][new_sum]:
                visited[new_remainder][new_sum] = True
                new_string = current.number_string + str(digit)
                queue.append(Element(new_remainder, new_sum, new_string))
    
    return -1

# Test the function
A, B = 50, 2
result = find_minimum_number(A, B)
print(f"Minimum number divisible by {A} with digit sum {B}: {result}")
Minimum number divisible by 50 with digit sum 2: 200

How It Works

The algorithm explores all possible numbers by building them digit by digit. For each state, we track ?

  • Remainder: Current number modulo A

  • Digit sum: Sum of digits added so far

  • Number string: The actual number being constructed

The BFS ensures we find the minimum number first, as shorter numbers are explored before longer ones.

Example Walkthrough

For A = 50, B = 2 ?

  • Start with remainder = 0, sum = 0

  • Try digits: 1 gives remainder = 1, sum = 1

  • Try digits: 2 gives remainder = 2, sum = 2

  • From "2", append 0: remainder = 20, sum = 2

  • From "20", append 0: remainder = 0, sum = 2 ?

  • Return 200

Time and Space Complexity

  • Time Complexity: O(A × B × 10) for exploring all states

  • Space Complexity: O(A × B) for the visited array and queue

Conclusion

This BFS approach efficiently finds the minimum positive integer divisible by A with digit sum B. The algorithm uses state tracking to avoid infinite loops and guarantees the smallest solution due to breadth-first exploration.

Updated on: 2026-03-25T09:35:11+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements