

- A = X + Y
- B = X xor Y
The task is to make ten a minimum as potential. If it is not possible to find any valid values for X and Y then print -1.
Examples:
Input : A = 12, B = 8 Output : X = 2, Y = 10 Input : A = 12, B = 9 Output : -1
Let ’ s take a look at some bite in X, which is peer to 1. If the respective bit in Y is peer to 0, then one can swap these two bits, frankincense reducing X and increasing Y without changing their sum and xor. We can conclude that if some moment in X is equal to 1 then the respective bit in Y is besides peer to 1. frankincense, Y = X + B. Taking into account that X + Y = X + X + B = A, one can obtain the follow rule for finding X and Y :
- X = (A – B) / 2
- Y = X + B = (A + B) / 2
One should besides notice that if A < B or A and B have different parity bit, then the suffice doesn ’ thyroxine exist and end product is -1. If x and ( A – X ) not equal to X then the answer is besides -1.
Below is the execution of the above approach :
C++
#include using namespace std; void findValues( int a, int b) { if ((a - b) % 2 == 1) { cout << "-1" ; return ; } cout << (a - b) / 2 << " " << (a + b) / 2; } int main() { int a = 12, b = 8; findValues(a, b); return 0; } |
Java
import java.io.*; class GFG { static void findValues( int a, int b) { if ((a - b) % 2 == 1 ) { System.out.println ( "-1" ); return ; } System.out.println (((a - b) / 2 )+ " " + ((a + b) / 2 )); } public static void main (String[] args) { int a = 12 , b = 8 ; findValues(a, b); } } |
Python3
def findValues(a, b): if ((a - b) % 2 = = 1 ): print ( "-1" ); return ; print ((a - b) / / 2 , (a + b) / / 2 );
|
C#
using System; class GFG { static void findValues( int a, int b) { if ((a - b) % 2 == 1) { Console.Write ( "-1" ); return ; } Console.WriteLine(((a - b) / 2)+ " " + ((a + b) / 2)); } static public void Main () { int a = 12, b = 8; findValues(a, b); } } |
PHP
function findValues( $a , $b ) { if (( $a - $b ) % 2 == 1) { echo "-1" ; return ; } echo ( $a - $b ) / 2, " " , ( $a + $b ) / 2; } $a = 12; $b = 8; findValues( $a , $b ); ?> |
Javascript
|
Output:
2 10
Time Complexity : O ( 1 )
Auxiliary Space : O ( 1 )
My Personal Notes
arrow_drop_up