Minimum number of operations required to reduce N to 1 | 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 ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; Driver code
def count_minimum_operations ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT if ( n % 3 == 0 ) : NEW_LINE INDENT n //= 3 NEW_LINE DEDENT elif ( n % 3 == 1 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT n += 1 NEW_LINE DEDENT DEDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE ans = count_minimum_operations ( n ) NEW_LINE print ( ans ) NEW_LINE DEDENT