Count ordered pairs of positive numbers such that their sum is S and XOR is K

Given a sum S and a number K. The task is to count all possible ordered pairs (a, b) of positive numbers such that the two positive integers a and b have a sum of S and a bitwise-XOR of K.

Examples:

Input : S = 9, K = 5
Output : 4
The ordered pairs are  (2, 7), (3, 6), (6, 3), (7, 2)

Input : S = 2, K = 2
Output : 0
There are no such ordered pair.

Approach:

For any two integers a and b,

Sum S = a + b can be written as S = (a \oplus b) + (a & b)*2

Where a \oplus b is the bitwise XOR and a & b is bitwise AND of the two number a and b respectively.

This is because \oplus is non-carrying binary addition. Thus we can write a & b = (S-K)/2 where S=(a + b) and K = (a \oplus b).

If (S-K) is odd or (S-K) less than 0,

  • then there is no such ordered pair.

Now, for each bit, a&b \in{0, 1} and (a \oplus b)\in{0, 1}.

  • If, (a \oplus b) = 0 then ai = bi, so we have one possibility: ai = bi = (ai & bi).
  • If, (a \oplus b) = 1 then we must have (ai & bi) = 0 (otherwise the output is 0), and we have two choices: either (ai = 1 and bi = 0) or (ai = 0 and bi = 1).

Where, ai is the i-th bit in a and bi is the i-th bit in b.

Thus, the answer is 2{^p}, where p is the number of set bits in K.

We will subtract 2 if S and K are equal because a and b must be positive(>0).

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count ordered pairs of
// positive numbers such that their
// sum is S and XOR is K
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to count ordered pairs of
// positive numbers such that their
// sum is S and XOR is K
int countPairs(int s, int K)
{
    // Check if no such pair exists
    if (K > s || (s - K) % 2) {
        return 0;
    }
  
    if ((s - K) / 2 & K) {
        return 0;
    }
  
    // Calculate set bits in K
    int setBits = __builtin_popcount(K);
  
    // Calculate pairs
    int pairsCount = pow(2, setBits);
  
    // If s = k, subtract 2 from result
    if (s == K)
        pairsCount -= 2;
  
    return pairsCount;
}
  
// Driver code
int main()
{
    int s = 9, K = 5;
  
    cout << countPairs(s, K);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count ordered pairs of 
// positive numbers such that their 
// sum is S and XOR is K 
  
class GFG {
  
// Function to count ordered pairs of 
// positive numbers such that their 
// sum is S and XOR is K 
    static int countPairs(int s, int K) {
        // Check if no such pair exists 
        if (K > s || (s - K) % 2 ==1) {
            return 0;
        }
  
        if ((s - K) / 2 == 1 & K == 1) {
            return 0;
        }
  
        // Calculate set bits in K 
        int setBits = __builtin_popcount(K);
  
        // Calculate pairs 
        int pairsCount = (int) Math.pow(2, setBits);
  
        // If s = k, subtract 2 from result 
        if (s == K) {
            pairsCount -= 2;
        }
  
        return pairsCount;
    }
  
    static int __builtin_popcount(int n) {
        /* Function to get no of set  
    bits in binary representation  
    of positive integer n */
  
        int count = 0;
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }
  
// Driver program to test above function 
    public static void main(String[] args) {
        int s = 9, K = 5;
        System.out.println(countPairs(s, K));
  
    }
  
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count ordered pairs of 
# positive numbers such that their 
# sum is S and XOR is K 
  
# Function to count ordered pairs of 
# positive numbers such that their 
# sum is S and XOR is K 
def countPairs(s,K):
    if(K>s or (s-K)%2==1):
        return 0
          
    # Calculate set bits in k
    setBits=(str(bin(K))[2:]).count("1")
  
    # Calculate pairs
    pairsCount = pow(2,setBits)
  
    # If s = k, subtract 2 from result
    if(s==K):
        pairsCount-=2
  
    return pairsCount
  
# Driver code
if __name__=='__main__':
    s,K=9,5
    print(countPairs(s,K))
  
# This code is contributed by 
# Indrajit Sinha.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count ordered pairs 
// of positive numbers such that their 
// sum is S and XOR is K 
using System;
                      
class GFG
{
  
// Function to count ordered pairs of 
// positive numbers such that their 
// sum is S and XOR is K 
static int countPairs(int s, int K)
{
    // Check if no such pair exists 
    if (K > s || (s - K) % 2 ==1) 
    {
        return 0;
    }
  
    if ((s - K) / 2 == 1 & K == 1)
    {
        return 0;
    }
  
    // Calculate set bits in K 
    int setBits = __builtin_popcount(K);
  
    // Calculate pairs 
    int pairsCount = (int) Math.Pow(2, setBits);
  
    // If s = k, subtract 2 from result 
    if (s == K) 
    {
        pairsCount -= 2;
    }
  
    return pairsCount;
}
  
static int __builtin_popcount(int n) 
{
    /* Function to get no of set 
    bits in binary representation 
    of positive integer n */
    int count = 0;
    while (n > 0) 
    {
        count += n & 1;
        n >>= 1;
    }
    return count;
}
  
// Driver Code
public static void Main()
{
    int s = 9, K = 5;
    Console.Write(countPairs(s, K)); 
}
}
  
// This code is contributed 
// by Rajput-Ji

chevron_right


PHP

$s || ($s – $K) % 2 == 1)
{
return 0;
}

if (($s – $K) / 2 == 1 & $K == 1)
{
return 0;
}

// Calculate set bits in K
$setBits = __builtin_popcount($K);

// Calculate pairs
$pairsCount = (int)pow(2, $setBits);

// If s = k, subtract 2 from result
if ($s == $K)
{
$pairsCount -= 2;
}

return $pairsCount;
}

function __builtin_popcount($n)
{
/* Function to get no of set
bits in binary representation
of positive integer n */
$count = 0;
while ($n > 0)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}

// Driver Code
$s = 9; $K = 5;
echo countPairs($s, $K) . “\n”;

// This code is contributed
// by Akanksha Rai

Output:

4

Time Complexity: O(log(K))



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.