Find two numbers from their sum and XOR - GeeksforGeeks

09 Nov, 2020
Given the sum and xor of two numbers X and Y s.t. sum and xor , we need to find the numbers minimizing the value of X.
Examples :
Input : S = 17
        X = 13
Output : a = 2
         b = 15

Input : S = 1870807699 
        X = 259801747
Output : a = 805502976
         b = 1065304723

Input : S = 1639
        X = 1176
Output : No such numbers exist

Variables Used:X ==> XOR of two numbersS ==> Sum of two numbersX[i] ==> Value of i-th bit in XS[i] ==> Value of i-th bit in S
A simple solution is to generate all possible pairs with given XOR. To generate all pairs, we can follow below rules.
If X[i] is 1, then both a[i] and b[i] should be different, we have two cases.If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std;  // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S,             unsigned long int X){    unsigned long int A = (S - X)/2;      int a = 0, b = 0;      // Traverse through all bits    for (int i=0; i<8*sizeof(S); i++)    {        unsigned long int Xi = (X & (1 << i));        unsigned long int Ai = (A & (1 << i));        if (Xi == 0 && Ai == 0)        {            // Let us leave bits as 0.        }        else if (Xi == 0 && Ai > 0)        {            a = ((1 << i) | a);             b = ((1 << i) | b);         }        else if (Xi > 0 && Ai == 0)        {            a = ((1 << i) | a);               // We leave i-th bit of b as 0.        }        else // (Xi == 1 && Ai == 1)        {            cout << "Not Possible";            return;        }    }      cout << "a = " << a << endl << "b = " << b;}  // Driver functionint main(){    unsigned long int S = 17, X = 13;    compute(S, X);    return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;         final int LONG_FIELD_SIZE     = 8;      // Traverse through all bits     for (int i=0; i<8*LONG_FIELD_SIZE; i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             System.out.println("Not Possible");             return;         }     }       System.out.println("a = " + a +"\nb = " + b); }   // Driver function     public static void main(String[] args) {        long S = 17, X = 13;     compute(S, X);       }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum.    # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X):    A = (S - X)//2    a = 0    b = 0      # Traverse through all bits    for i in range(64):        Xi = (X & (1 << i))        Ai = (A & (1 << i))        if (Xi == 0 and Ai == 0):            # Let us leave bits as 0.            pass                      elif (Xi == 0 and Ai > 0):            a = ((1 << i) | a)             b = ((1 << i) | b)                   elif (Xi > 0 and Ai == 0):            a = ((1 << i) | a)             # We leave i-th bit of b as 0.          else: # (Xi == 1 and Ai == 1)            print("Not Possible")            return      print("a = ",a)    print("b =", b)    # Driver functionS = 17X = 13compute(S, X)  # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System;  public class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;          // Traverse through all bits     for (int i=0; i<8*sizeof(long); i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             Console.WriteLine("Not Possible");             return;         }     }       Console.WriteLine("a = " + a +"\nb = " + b); }   // Driver function     public static void Main() {        long S = 17, X = 13;         compute(S, X);     }}// This code is contributed by RAJPUT-JIOutputa = 15
b = 2
Time complexity of the above approach  where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes
arrow_drop_upSave
If X[i] is 1, then both a[i] and b[i] should be different, we have two cases.
If X[i] is 0, then both a[i] and b[i] should be same. we have two cases.So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.An efficient solution is based on below fact.S = X + 2*Awhere A = a AND bWe can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.So we can find A = (S – X)/2.Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)Let the summation be S and XOR be X.Below is the implementation of above approach:C++JavaPython3C#C++// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std;  // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S,             unsigned long int X){    unsigned long int A = (S - X)/2;      int a = 0, b = 0;      // Traverse through all bits    for (int i=0; i<8*sizeof(S); i++)    {        unsigned long int Xi = (X & (1 << i));        unsigned long int Ai = (A & (1 << i));        if (Xi == 0 && Ai == 0)        {            // Let us leave bits as 0.        }        else if (Xi == 0 && Ai > 0)        {            a = ((1 << i) | a);             b = ((1 << i) | b);         }        else if (Xi > 0 && Ai == 0)        {            a = ((1 << i) | a);               // We leave i-th bit of b as 0.        }        else // (Xi == 1 && Ai == 1)        {            cout << "Not Possible";            return;        }    }      cout << "a = " << a << endl << "b = " << b;}  // Driver functionint main(){    unsigned long int S = 17, X = 13;    compute(S, X);    return 0;}Java// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;         final int LONG_FIELD_SIZE     = 8;      // Traverse through all bits     for (int i=0; i<8*LONG_FIELD_SIZE; i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             System.out.println("Not Possible");             return;         }     }       System.out.println("a = " + a +"\nb = " + b); }   // Driver function     public static void main(String[] args) {        long S = 17, X = 13;     compute(S, X);       }}// This code is contributed by RAJPUT-JIPython3# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum.    # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X):    A = (S - X)//2    a = 0    b = 0      # Traverse through all bits    for i in range(64):        Xi = (X & (1 << i))        Ai = (A & (1 << i))        if (Xi == 0 and Ai == 0):            # Let us leave bits as 0.            pass                      elif (Xi == 0 and Ai > 0):            a = ((1 << i) | a)             b = ((1 << i) | b)                   elif (Xi > 0 and Ai == 0):            a = ((1 << i) | a)             # We leave i-th bit of b as 0.          else: # (Xi == 1 and Ai == 1)            print("Not Possible")            return      print("a = ",a)    print("b =", b)    # Driver functionS = 17X = 13compute(S, X)  # This code is contributed by ankush_953C#// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System;  public class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;          // Traverse through all bits     for (int i=0; i<8*sizeof(long); i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             Console.WriteLine("Not Possible");             return;         }     }       Console.WriteLine("a = " + a +"\nb = " + b); }   // Driver function     public static void Main() {        long S = 17, X = 13;         compute(S, X);     }}// This code is contributed by RAJPUT-JIOutputa = 15
b = 2
Time complexity of the above approach  where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes
arrow_drop_upSave
So we generate 2^n possible pairs where n is number of bits in X. Then for every pair, we check if its sum is S or not.
An efficient solution is based on below fact.
S = X + 2*Awhere A = a AND b
We can verify above fact using the sum process. In sum, whenever we see both bits 1 (i.e., AND is 1), we make resultant bit 0 and add 1 as carry, which means every bit in AND is left shifted by 1 OR value of AND is multiplied by 2 and added.
So we can find A = (S – X)/2.
Once we find A, we can find all bits of ‘a’ and ‘b’ using below rules.
If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)
If X[i] = 0 and A[i] = 0, then a[i] = b[i] = 0. Only one possibility for this bit.
If X[i] = 0 and A[i] = 1, then a[i] = b[i] = 1. Only one possibility for this bit.
If X[i] = 1 and A[i] = 0, then (a[i] = 1 and b[i] = 0) or (a[i] = 0 and b[i] = 1), we can pick any of the two.
If X[i] = 1 and A[i] = 1, result not possible (Note X[i] = 1 means different bits)
Let the summation be S and XOR be X.
Below is the implementation of above approach:
C++
Java
Python3
C#
// CPP program to find two numbers with// given Sum and XOR such that value of// first number is minimum.#include <iostream>using namespace std;  // Function that takes in the sum and XOR// of two numbers and generates the two // numbers such that the value of X is// minimizedvoid compute(unsigned long int S,             unsigned long int X){    unsigned long int A = (S - X)/2;      int a = 0, b = 0;      // Traverse through all bits    for (int i=0; i<8*sizeof(S); i++)    {        unsigned long int Xi = (X & (1 << i));        unsigned long int Ai = (A & (1 << i));        if (Xi == 0 && Ai == 0)        {            // Let us leave bits as 0.        }        else if (Xi == 0 && Ai > 0)        {            a = ((1 << i) | a);             b = ((1 << i) | b);         }        else if (Xi > 0 && Ai == 0)        {            a = ((1 << i) | a);               // We leave i-th bit of b as 0.        }        else // (Xi == 1 && Ai == 1)        {            cout << "Not Possible";            return;        }    }      cout << "a = " << a << endl << "b = " << b;}  // Driver functionint main(){    unsigned long int S = 17, X = 13;    compute(S, X);    return 0;}
// Java program to find two numbers with // given Sum and XOR such that value of // first number is minimum. class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;         final int LONG_FIELD_SIZE     = 8;      // Traverse through all bits     for (int i=0; i<8*LONG_FIELD_SIZE; i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             System.out.println("Not Possible");             return;         }     }       System.out.println("a = " + a +"\nb = " + b); }   // Driver function     public static void main(String[] args) {        long S = 17, X = 13;     compute(S, X);       }}// This code is contributed by RAJPUT-JI
# Python program to find two numbers with# given Sum and XOR such that value of# first number is minimum.    # Function that takes in the sum and XOR# of two numbers and generates the two # numbers such that the value of X is# minimizeddef compute(S, X):    A = (S - X)//2    a = 0    b = 0      # Traverse through all bits    for i in range(64):        Xi = (X & (1 << i))        Ai = (A & (1 << i))        if (Xi == 0 and Ai == 0):            # Let us leave bits as 0.            pass                      elif (Xi == 0 and Ai > 0):            a = ((1 << i) | a)             b = ((1 << i) | b)                   elif (Xi > 0 and Ai == 0):            a = ((1 << i) | a)             # We leave i-th bit of b as 0.          else: # (Xi == 1 and Ai == 1)            print("Not Possible")            return      print("a = ",a)    print("b =", b)    # Driver functionS = 17X = 13compute(S, X)  # This code is contributed by ankush_953
// C# program to find two numbers with // given Sum and XOR such that value of // first number is minimum. using System;  public class GFG {  // Function that takes in the sum and XOR // of two numbers and generates the two // numbers such that the value of X is // minimized static void compute(long S, long  X) {     long A = (S - X)/2;     int a = 0, b = 0;          // Traverse through all bits     for (int i=0; i<8*sizeof(long); i++)     {         long Xi = (X & (1 << i));         long Ai = (A & (1 << i));         if (Xi == 0 && Ai == 0)         {             // Let us leave bits as 0.         }         else if (Xi == 0 && Ai > 0)         {             a = ((1 << i) | a);             b = ((1 << i) | b);         }         else if (Xi > 0 && Ai == 0)         {             a = ((1 << i) | a);               // We leave i-th bit of b as 0.         }         else // (Xi == 1 && Ai == 1)         {             Console.WriteLine("Not Possible");             return;         }     }       Console.WriteLine("a = " + a +"\nb = " + b); }   // Driver function     public static void Main() {        long S = 17, X = 13;         compute(S, X);     }}// This code is contributed by RAJPUT-JI
a = 15
b = 2

Time complexity of the above approach  where b is number of bits in S.YouTubeGeeksforGeeks507K subscribersFind two numbers from their sum and XOR | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qapfPE5oBwA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
The_king_of_Knight
kartik
Rajput-Ji
ankush_953
Bitwise-XOR
Walmart
Bit Magic
Competitive Programming
Walmart
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Josephus problem | Set 1 (A O(n) Solution)
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming