# Count ordered pairs of positive numbers such that their sum is S and XOR is K in C++

C++Server Side ProgrammingProgramming

We are given two numbers S and K. The goal is to find ordered pairs of positive numbers such that their sum is S and XOR is K.

We will do this by starting from i=1 to i<S-1 and j=i+1 to j<S. If any pair (i,j) has sum==S and i^j==K (XOR). Then increment count by 2 as (i,j) and (j,i) both will be counted as different pairs.

Let’s understand with examples.

Input

S=10 K=4

Output

Ordered pairs such that sum is S and XOR is K: 2

Explanation

Pairs will be (3,7) and (7,3)

Input

S=12 K=6

Output

Ordered pairs such that sum is S and XOR is K: 0

Explanation

No such pairs possible.

## Approach used in the below program is as follows

• We take integers S and K.

• Function sumXOR(int s, int k) takes s and k and returns the count of ordered pairs with sum=s and xor=k

• Take the initial variable count as 0 for pairs.

• Traverse using two for loops for making pairs.

• Start from i=1 to i<s-1. And j=i+1 to j<s-1.

• Now for each pair (i,j) check if (i+j==s) && (i^j==k). If true increment count by 2 as (i,j) and (j,i) both are different pairs.

• At the end of all loops count will have a total number of such pairs.

• Return the count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int sumXOR(int s, int k){
int count = 0;
for (int i = 1; i < s; i++){
for(int j=i+1; j<s-1; j++){
if( (i+j)==s && (i^j)==k){
count+=2; //(i,j) and (j,i) are two pairs
}
}
}
return count;
}
int main(){
int S = 9, K = 5;
cout <<"Ordered pairs such that sum is S and XOR is K: "<< sumXOR(S,K);
return 0;
}

## Output

If we run the above code it will generate the following output −

Ordered pairs such that sum is S and XOR is K: 4