Check if N can be obtained by repetitive addition or subtraction of two given numbers
Given three positive integers N, A, and B, the task is to check if it is possible to obtain N by adding or subtracting A and B multiple times.
Input: N = 11, A = 2, B = 5
Explanation: 11 = 5 + 5 + 5 – 2 -2
Input: N = 11, A = 2, B = 4
Explanation: Not possible to obtain 11 from 2 and 4 only.
Follow the steps below to solve the problem:
- The task is to check if it is possible to add or subtract A and B multiple times and obtain N as the end result.
- Hence, in terms of linear equation, it can be written as:
Ax + By = N,
where x and y represent the number of times A and B are added or subtracted. Negative x represents A is subtracted x times and similarly, negative y represents B is subtracted y times
- Now, the aim is to find the integral solutions for the above equation. Here, it is quite valid to use Extended Euclid Algorithm which says that the solutions exist if and only if N % gcd(a, b) is 0.
Below is the implementation of the above approach:
Time Complexity: O(log(min(A, B))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.