Given a number N. The task is to reduce the given number N to 1 in the minimum number of steps. You can perform any one of the below operations in each step.
- Operation 1: If the number is even then you can divide the number by 2.
- Operation 2: If the number is odd then you are allowed to perform either (n+1) or (n-1).
You need to print the minimum number of steps required to reduce the number N to 1 by performing the above operations.
Input : n = 15 Output : 5 15 is odd 15+1=16 16 is even 16/2=8 8 is even 8/2=4 4 is even 4/2=2 2 is even 2/2=1 Input : n = 7 Output : 4 7->6 6->3 3->2 2->1
The idea is to recursively compute the minimum number of steps required.
- If the number is even, then we are allowed to only divide the number by 2.
- But, when the number is Odd, we can either increment or decrement it by 1. So, we will use recursion for both n-1 and n+1 and return the one with the minimum number of operations.
Below is the implementation of above approach:
- Number of array elements derivable from D after performing certain operations
- Minimum number operations required to convert n to m | Set-2
- Maximum number of given operations to remove the entire string
- Find minimum number of merge operations to make an array palindrome
- Number of ways to divide a given number as a set of integers in decreasing order
- Total number of possible Binary Search Trees using Catalan Number
- Number of ways to represent a number as sum of k fibonacci numbers
- Find the smallest number whose digits multiply to a given number n
- Build Lowest Number by Removing n digits from a given number
- Minimum number of squares whose sum equals to given number n
- Minimum number of cubes whose sum equals to given number N
- Find the Number Occurring Odd Number of Times
- Number of subsets with zero sum
- Happy Number
- Number of subsequences with zero sum
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.