Check if N can be represented as sum of integers chosen from set {A, B} in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number target. We have another two numbers A and B. We have to check whether we can get target by adding A and B as many times as we want.

So, if the input is like Target = 26 A = 5 B = 7, then the output will be True as we can get 26 by adding A and B like (7 + 7 + 7 + 5).

To solve this, we will follow these steps −

  • Define a function util() . This will take x, a, b, is_ok, target
  • if x > target, then
    • return
  • if is_ok[x] is True, then
    • return
  • is_ok[x] := True
  • util(x + a, a, b, is_ok, target)
  • util(x + b, a, b, is_ok, target)
  • From the main method do the following −
  • is_ok := an array of size (target + 1) and fill with False
  • util(0, a, b, is_ok, target)
  • return is_ok[target]

Example

Let us see the following implementation to get better understanding −

 Live Demo

def util(x, a, b, is_ok, target):
   if x > target:
      return
   if is_ok[x]:
      return
   is_ok[x] = True
   util(x + a, a, b, is_ok, target)
   util(x + b, a, b, is_ok, target)
def solve(target, a, b):
   is_ok = [False] * (target + 1)
   util(0, a, b, is_ok, target)
   return is_ok[target]
target = 26
A = 5
B = 7
print(solve(target, A, B))

Input

26, 5, 7

Output

True
raja
Published on 19-Jan-2021 05:09:07
Advertisements