Given an integer element ‘N’, the task is to find the minimum number of operations that need to be performed to make ‘N’ equal to 1.
The allowed operations to be performed are:
- Decrement N by 1.
- Increment N by 1.
- If N is a multiple of 3, you can divide N by 3.
Input: N = 4
4 – 1 = 3
3 / 3 = 1
The minimum number of operations required is 2.
Input: N = 8
8 + 1 = 9
9 / 3 = 3
3 / 3 = 1
The minimum number of operations required is 3.
- If the number is a multiple of 3, divide it by 3.
- If the number modulo 3 is 1, decrement it by 1.
- If the number modulo 3 is 2, increment it by 1.
- There is an exception when the number is equal to 2, in this case the number should be decremented by 1.
- Repeat the above steps until the number is greater than 1 and print the count of operations performed in the end.
Below is the implementation of the above approach:
# Python3 implementation of above approach
# Function that returns the minimum
# number of operations to be performed
# to reduce the number to 1
# To stores the total number of
# operations to be performed
count = 0
while (n > 1) :
# if n is divisible by 3
# then reduce it to n / 3
if (n % 3 == 0):
n //= 3
# if n modulo 3 is 1
# decrement it by 1
elif (n % 3 == 1):
n -= 1
if (n == 2):
n -= 1
# if n modulo 3 is 2
# then increment it by 1
n += 1
# update the counter
count += 1
# Driver code
if __name__ ==”__main__”:
n = 4
ans = count_minimum_operations(n)
# This code is contributed
# by ChitraNayal
- Count the number of operations required to reduce the given number
- Count operations of the given type required to reduce N to 0
- Minimum number operations required to convert n to m | Set-2
- Minimum number of operations required to delete all elements of the array
- Find the minimum number of operations required to make all array elements equal
- Minimum no. of operations required to make all Array Elements Zero
- Minimum operations required to make all the array elements equal
- Minimum operations of the given type required to make a complete graph
- Minimum operations required to make all the elements distinct in an array
- Minimum operations required to modify the array such that parity of adjacent elements is different
- Count the number of carry operations required to add two numbers
- Find the number of operations required to make all array elements Equal
- Find maximum operations to reduce N to 1
- Minimum number of given powers of 2 required to represent a number
- Minimum prime number operations to convert A to B
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.