Count of distinct values till C formed by adding or substracting A, B, or 0 any number of times
Given three integers A, B and C. You can add or substract A, B, or 0 any number of times to form new values in range 0 < final_value ≤ C. The task is to find the count of such distinct final values possible.
Input : A = 2, B = 3, C = 10
Possible values are :
0 + 3 – 2 =1
0 + 2 = 2
0 + 3 = 3
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Input : A = 10, B = 2, C = 10
Approach: The idea is to use the GCD g of A and B.
The above approach works Because every distinct possible value is xA+yB
- If A can be written as g×a, B can be written as g×b
- Then, A required final value can be written as xAg+yBg = (x*g*a + y*g*b) = g*(xa+yb)
- Since maximum value possible is C, therefore C = g*(xa+yb).
- Hence count of possible such values = C/g, which is the required answer.
Below is the implementation of the above approach :
Time Complexity : O(log(max(A, B))
Space Complexity : 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.