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
function count_minimum_operations ( n ) { let count = 0 ; while ( n > 1 ) { if ( n % 3 == 0 ) n /= 3 ; else if ( n % 3 == 1 ) n -- ; else { if ( n == 2 ) n -- ; else n ++ ; } count ++ ; } return count ; } let n = 4 ; let ans = count_minimum_operations ( n ) ; document . write ( ans ) ;