Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M
Given a number N, the task is to form N (from 0) by adding 1 or 2 in the minimum number of operations X such that X is divisible by M.
Input: N = 10, M = 2
Output: X = 6
Taken operations are 2 2 2 2 1 1
X = 6 which is divisible by 2
Input: N = 17, M = 4
- As we can take either 1 or 2 steps at a time, so we can say that minimum no. of steps taken is n/2, and the maximum no. of steps is n, irrespective of that the no. of steps are divisible by m.
- So we have to count n/2 steps to get a minimum number of steps. Now if n is even, then a minimum number of steps will be n/2, but if it is odd, then it will be n/2+1, irrespective of that the no. of steps are divisible by m. To make minimum steps of a multiple of m we can do floor((minimum_steps + m – 1)/m) * m
- Also if n is less than m, then it is not possible to find the minimum number of steps, and in that case, we will return -1.
Below is the implementation of above approach:
Time Complexity: O(1)