C++ code to find minimum operations to make numbers c and d

Suppose we have two numbers c and d. Amal has two numbers a and b initially both are zero. Amal wants to perform some operation on them. Before performing each operation, some positive integer k is picked, which is then used to perform one of the following operations −

  • add number k to both a and b, or

  • add number k to a and subtract k from b, or

  • add number k to b and subtract k from a.

We have to find the minimum number of operations needed to make a and b equal to c and d respectively. If not possible, return -1.

So, if the input is like c = 3; d = 5, then the output will be 2, because for k = 1, we get the numbers (1, 1), for k = 8, the pair can be (-7, 9), for k = 7, it can be (0, 2) and for k = 3, it can be (3, 5)


To solve this, we will follow these steps −

if (c ^ d) is odd, then:
   return -1
otherwise when c is same as 0 and d is same as 0, then:
   return 0
otherwise when c is same as d, then:
   return 1
   return 2


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int c, int d){
   if ((c ^ d) & 1)
      return -1;
   else if (c == 0 && d == 0)
      return 0;
   else if (c == d)
      return 1;
      return 2;
int main(){
   int c = 3;
   int d = 5;
   cout << solve(c, d) << endl;


3, 5



Updated on: 11-Mar-2022


Kickstart Your Career

Get certified by completing the course

Get Started