
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if N can be represented as sum of integers chosen from set {A, B} in Python
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 −
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
- Related Articles
- Program to check n can be represented as sum of k primes or not in Python
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- 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 Python
- Program to check n can be shown as sum of k or not in Python
- Check if an integer can be expressed as a sum of two semi-primes in Python
- Check if a prime number can be expressed as sum of two Prime Numbers in Python
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Check if a number can be expressed as a^b in C++
- Check if a number can be expressed as sum two abundant numbers in C++
- Count numbers which can be represented as sum of same parity primes in C++
- Check if is possible to get given sum from a given set of elements in Python
- Check if N is divisible by a number which is composed of the digits from the set {A, B} in Python
- Check if a given number can be represented in given a no. of digits in any base in C++

Advertisements