Minimum number of operations required to reduce N to 1 | C ++ 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 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_minimum_operations ( long long n ) { int 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 ; } int main ( ) { long long n = 4 ; long long ans = count_minimum_operations ( n ) ; cout << ans << endl ; return 0 ; }