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


Suppose we have two numbers A and B, we have to find the minimum positive number M so that M is divisible by A and the sum of the digits of M is same as B. So, if there is no such result, then return -1.

So, if the input is like A = 50, B = 2, then the output will be 200 as this is divisible by 50 and sum of its digit = 2 + 0 + 0 = 2.

To solve this, we will follow these steps −

  • Define one element type container, that contains two numbers a and b and one string

  • que := a new list

  • elem := a new element with (0, 0, blank string)

  • visited[0, 0] := 1

  • insert elem at the end of que

  • while size of que > 0, do

    • temp_elem := delete first element from que

    • if temp_elem.a is 0 and temp_elem.b is b, then

      • return integer of temp_elem.string

    • for i in range 0 to 9, do

      • x :=(temp_elem.a * 10 + i) mod a

      • y := temp_elem.b + i

      • if y <= b and visited[x, y] is False, then

        • visited[x, y] := 1

        • insert new element with x, y and temp_elem.string concatenate i into que

  • return -1

Example 

Let us see the following implementation to get better understanding −

 Live Demo

visited = [[0 for x in range(501)] for y in range(5001)]
class Element:
   def __init__(self, a, b, string):
      self.a = a
      self.b = b
      self.string = string
def get_number(a, b):
   que = []
   elem = Element(0, 0, "")
   visited[0][0] = 1
   que.append(elem)
   while len(que) > 0:
      temp_elem = que.pop(0)
      if temp_elem.a == 0 and temp_elem.b == b:
         return int(temp_elem.string)
      for i in range(0, 10):
         x = (temp_elem.a * 10 + i) % a
         y = temp_elem.b + i
         if y <= b and visited[x][y] == False:
            visited[x][y] = 1
            que.append(Element(x, y, temp_elem.string + str(i)))
   return -1

a, b = 50, 2
print(get_number(a, b))

Input

50, 2

Output

200

Updated on: 20-Aug-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements