Given three positive integers N, K, and M, the task is to find the number to be added to N to obtain the sum of first M multiples of K.
Input: N = 17, K = 3, M = 4
Sum of first 4 multiples of 3 = (3 + 6 + 9 + 12) = 30.
Therefore, the value to be added to 17 is (30 – 17) = 13.
Therefore, the required output is 13.
Input: N = 5, K = 2, M = 1
Sum of first 1 multiples of 2 is 2.
The value to be added to 5 to get 2 is (2 – 5) = -3
Approach: Follow the steps below to solve the problem:
- Calculate the sum of first M multiples of K, which will be equal to K * (1 + 2 + 3 + … M) = K * M * (M + 1) / 2.
- Initialize a variable, say res, to store the number required to be added to N to obtain sum.
- Therefore, res will be equal to sum – N. Pritn the value of res.
Below is the implementation of the above approach:
Time Complexity: O(1)
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.