Minimum operations to make two numbers equal | C ++ implementation of the above approach ; Function to find the minimum no of operations ; find the maximum of two and store it in p ; increase it until it is achievable from given n and m ; Here value added to n and m will be S ( n ) = p - n + p - m ; check whether integer value of n exist by the formula n = ( - 1 + sqrt ( 1 + 8 * S ( n ) ) ) / 2 ; Driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int n , int m ) { int a = 0 , k = 1 ; int p = max ( n , m ) ; while ( n != m ) { float s = ( float ) ( p - n + p - m ) ; float q = ( -1 + sqrt ( 8 * s + 1 ) ) / 2 ; if ( q - floor ( q ) == 0 ) { a = q ; n = m ; } p = p + 1 ; } return a ; } int main ( ) { int n = 1 , m = 3 ; cout << minOperations ( n , m ) ; return 0 ; }