Given an integer N, the task is to find all non-negative pairs (A, B) such that the sum of Bitwise OR and Bitwise AND of A, B is equal to N, i.e., (A | B) + (A & B) = N.
Examples:
Input: N = 5
Output: (0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)
Explanation: All possible pairs satisfying the necessary conditions:
- (0 | 5) + (0 & 5) = 5 + 0 = 5
- (1 | 4) + (1 & 4) = 5 + 0 = 5
- (2 | 3) + (2 & 3) = 3 + 2 = 5
- (3 | 2) + (3 & 2) = 3 + 2 = 5
- (4 | 1) + (4 & 1) = 5 + 0 = 5
- (5 | 0) + (5 & 0) = 5 + 0 = 5
Input: N = 7
Output: (0, 7), (1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)
Explanation: All possible pairs satisfying the necessary conditions:
- (0 | 7) + (0 & 7) = 7 + 0 =7
- (1 | 6) + (1 & 6) = 7 + 0 =7
- (2 | 5) + (2 & 5) = 7 + 0 =7
- (3 | 4) + (3 & 4) = 7 + 0 =7
- (4 | 3) + (4 & 3) = 7 + 0 =7
- (5 | 2) + (5 & 2) = 7 + 0 =7
- (6 | 1) + (6 & 1) = 7 + 0 = 7
- (7 | 0) + (7 & 0) = 7 + 0 = 7
Naive Approach: The simplest approach is to iterate over the range [0, N] and print those pairs (A, B) that satisfy the condition (A | B) + (A & B) = N.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the observation that all those non-negative pairs whose sum is equal to N satisfy the given condition. Therefore, iterate over the range [0, N] using the variable i and print the pair i and (N – i).
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void findPairs( int N)
{
for ( int i = 0; i <= N; i++) {
cout << "(" << i << ", "
<< N - i << "), " ;
}
}
int main()
{
int N = 5;
findPairs(N);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG{
static void findPairs( int N)
{
for ( int i = 0 ; i <= N; i++)
{
System.out.print( "(" + i + ", " +
(N - i) + "), " );
}
}
public static void main(String[] args)
{
int N = 5 ;
findPairs(N);
}
}
|
Python3
def findPairs(N):
for i in range ( 0 , N + 1 ):
print ( "(" , i, "," ,
N - i, "), " , end = "")
if __name__ = = "__main__" :
N = 5
findPairs(N)
|
C#
using System;
class GFG{
static void findPairs( int N)
{
for ( int i = 0; i <= N; i++)
{
Console.Write( "(" + i + ", " +
(N - i) + "), " );
}
}
public static void Main()
{
int N = 5;
findPairs(N);
}
}
|
Javascript
<script>
function findPairs(N)
{
for (let i = 0; i <= N; i++)
{
document.write( "(" + i + ", " +
(N - i) + "), " );
}
}
let N = 5;
findPairs(N);
</script>
|
Output: (0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0),
Time Complexity: O(N)
Auxiliary Space: O(1)