- Related Questions & Answers
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- Check if a number can be expressed as a^b in Python
- Check if a number can be written as sum of three consecutive integers in C++
- Check if a number can be represented as sum of non zero powers of 2 in C++
- Check if a number can be expressed as a^b in C++
- Check if a prime number can be expressed as sum of two Prime Numbers in Python
- Check if an integer can be expressed as a sum of two semi-primes in Python
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Count numbers which can be represented as sum of same parity primes in C++
- Check if a number can be expressed as sum two abundant numbers in C++
- Check if N is divisible by a number which is composed of the digits from the set {A, B} in Python
- Check if a string follows a^n b^n pattern or not in Python
- How I can check if A is superclass of B in Python?
- Check if a number can be expressed as power in C++
- Smallest positive value that cannot be represented as sum of subarray JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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]

Let us see the following implementation to get better understanding −

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))

26, 5, 7

True

Advertisements