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((minumum_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 Cmplexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
- Split an array into groups of 3 such that X3 is divisible by X2 and X2 is divisible by X1
- Minimum number of operations required to reduce N to 1
- Reduce N to 1 with minimum number of given operations
- Minimum no. of operations required to make all Array Elements Zero
- Find minimum operations needed to make an Array beautiful
- Minimum operations to make frequency of all characters equal K
- Minimum operations required to change the array such that |arr[i] - M| <= 1
- Minimum cost to convert str1 to str2 with the given operations
- Minimum operations required to make the string satisfy the given condition
- Maximize the median of the given array after adding K elements to the same array
- Find the number of operations required to make all array elements Equal
- Number of array elements derivable from D after performing certain operations
- Check if the large number formed is divisible by 41 or not
- Number of pairs from the first N natural numbers whose sum is divisible by K
- Minimum adjacent swaps to move maximum and minimum to corners
- Maximum Possible Product in Array after performing given Operations
- Check if at least half array is reducible to zero by performing some operations
- Check whether str1 can be converted to str2 with the given operations
- Count elements that are divisible by at-least one element in another array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.