Wednesday, 27 Oct 2021

# Check if it is possible to construct an Array of size N having sum as S and XOR value as X

Given three numbers N, S and X the task is to find if it is possible to construct a sequence A of length N, where each A[i] >= 0 for 1 X + ( S – X)/2 + (S – X)/2 =  X + (S-X) => X + ( S – X)/2 + (S – X)/2 =  S and also this way: X ^( (S – X)/2 ^ (S-X)/2 ) = X ^ 0 = X. Hence, it is proved that for N == 3 there will always be such sequence and we can just return “Yes“. Case-4: When N == 2 and  (S%2 == X%2) and S >= X, assume  A + B == S  and (A^B) == X then ( A and B) == (S-X)/2  From the equation discussed above. Let C = A.B. On observing carefully it can be noticed that the bits of C are “1” only when A and B bits are “1” for that position and off otherwise. And X that is xor of A, B has on bit only when there are different bits that is at ith  position A has ‘0’ and B has ‘1’ or the just opposite: So looking at this sequence, assign every bits into variable A and B, C = ( S – X)/2. Assign A and B from C -> A = C, B = CNow add the X into A or B to assign all the ones into A and all zero to B so when we XOR both numbers then the added ‘1’ bits into A will just be opposite to what we added into B that is ‘0’. The fun part is when set bits of C coincides with some set bits of X then it will not give the desired xor of X, Now, A = C  + X, B = C. Now A+B = ( C + X) + C =  S and when XOR A.B equals X then it can be sure that that there exist such pair when A + B == S  and (A^B) == X; Follow the steps below to solve the problem:If S is greater than equal to X, and S%2 is equal to X%2 then perform the following steps, else return No.If n is greater than equal to 3, then return Yes.If n equals 1, and if S equals X, then return Yes else return No.If n equals to 2, initialize the variable C as (S-X)/2 and set variables A and B as C and add the value X to the variable A and if A^B equals X, then print Yes else print No.Below is the implementation of the above approach.C++#include using namespace std;  string findIfPossible(int N, int S, int X){    if (S >= X and S % 2 == X % 2) {                                  if (N >= 3) {            return “Yes”;        }        if (N == 1) {                                      if (S == X) {                return “Yes”;            }            else {                return “No”;            }        }                          if (N == 2) {              int C = (S – X) / 2;            int A = C;            int B = C;            A = A + X;            if (((A ^ B) == X)) {                return “Yes”;            }            else {                return “No”;            }        }    }    else {        return “No”;    }}  int main(){      int N = 3, S = 10, X = 4;      cout