Minimize increments or decrements by 2 to convert given value to a perfect square | Java program to implement the above approach ; Function to find the minimum number of operations required to make N a perfect square ; Stores count of operations by performing decrements ; Stores value of N ; Decrement the value of temp ; Stores square root of temp ; If temp is a perfect square ; Update temp ; Store count of operations by performing increments ; Increment the value of N ; Stores sqrt of N ; If N is a perfect square ; Update temp ; Return the minimum count ; Driver code
class GFG { static int MinimumOperationReq ( int N ) { int cntDecr = 0 ; int temp = N ; while ( temp > 0 ) { int X = ( int ) Math . sqrt ( temp ) ; if ( X * X == temp ) { break ; } temp = temp - 2 ; cntDecr += 1 ; } int cntIncr = 0 ; while ( true ) { int X = ( int ) Math . sqrt ( N ) ; if ( X * X == N ) { break ; } N = N + 2 ; cntIncr += 1 ; } return Math . min ( cntIncr , cntDecr ) ; } public static void main ( String args [ ] ) { int N = 15 ; System . out . print ( MinimumOperationReq ( N ) ) ; } }