Minimize increments or decrements by 2 to convert given value to a perfect square | 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
def MinimumOperationReq ( N ) : NEW_LINE INDENT cntDecr = 0 ; NEW_LINE temp = N ; NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT X = int ( pow ( temp , 1 / 2 ) ) NEW_LINE if ( X * X == temp ) : NEW_LINE INDENT break ; NEW_LINE DEDENT temp = temp - 2 ; NEW_LINE cntDecr += 1 ; NEW_LINE DEDENT cntIncr = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT X = int ( pow ( N , 1 / 2 ) ) NEW_LINE if ( X * X == N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT N = N + 2 ; NEW_LINE cntIncr += 1 ; NEW_LINE DEDENT return min ( cntIncr , cntDecr ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 ; NEW_LINE print ( MinimumOperationReq ( N ) ) ; NEW_LINE DEDENT