Suppose we have some weights like a^0, a^1, a^2, …, a^100, here 'a' is an integer, and we also have a weighing scale where weights can be put on both the sides of that scale. We have to check whether a particular item of weight W can be measured using these weights or not.
So, if the input is like a = 4, W = 17, then the output will be True the weights are a^0 = 1, a^1 = 4, a^2 = 16, we can get 16 + 1 = 17.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
found = False def util(idx, itemWt, weights, N): global found if found: return if itemWt == 0: found = True return if idx > N: return util(idx + 1, itemWt, weights, N) util(idx + 1, itemWt + weights[idx], weights, N) util(idx + 1, itemWt - weights[idx], weights, N) def solve(a, W): global found if a == 2 or a == 3: return True weights = [0] * 100 total_weights = 0 weights[0] = 1 i = 1 while True: weights[i] = weights[i - 1] * a total_weights += 1 if weights[i] > 10**7: break i += 1 util(0, W, weights, total_weights) if found: return True return False a = 4 W = 17 print(solve(a, W))
4, 17
True