Find triplet A, B, C having bitwise AND of bitwise OR with each other as K
Last Updated :
01 Apr, 2022
Given an integer K, the task is to find three distinct integers A, B and C such that ( A ∣ B ) & ( B ∣ C ) & ( C ∣ A ) = K, where | and & denotes bitwise OR and bitwise AND operation respectively. If there are multiple solutions, you may print any of them.
Examples:
Input: K = 3
Output: 1 2 3
Explanation: ( 1 ∣ 2 ) & ( 2 ∣ 3 ) & ( 3 ∣ 1 ) = 3 & 3 & 3 = 3
Input: K = 13
Output: 6 9 13
Naive Approach: A brute force approach is to run three nested loops and find all the three integer which satisfy the above expression .
Time Complexity: O(K3)
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved based on the following observation:
Every set bit of K must be present in (A|B), (B|C) and (A|C) which implies that every set bit of K must be present in at least 2 of A, B and C.
So, make two numbers same as K and the other 0. To make the two numbers distinct add a larger power of 2 (which is greater than K) to any of them.
Follow the steps mentioned below to solve the problem:
- Make A and B equal to K and C = 0.
- Now add a higher power of 2(which is greater than K) to B [Here using 227].
- Print the values of A, B and C.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printABC( int K)
{
cout << K << " " << K + (1 << 27)
<< " " << 0 << endl;
}
int main()
{
int K = 3;
printABC(K);
return 0;
}
|
Java
import java.io.*;
public class GFG {
static void printABC( int K)
{
System.out.println(K + " " + (K + ( 1 << 27 )) + " "
+ 0 );
}
public static void main(String[] args)
{
int K = 3 ;
printABC(K);
}
}
|
Python3
def printABC(K):
print (K, K + ( 1 << 27 ), 0 )
K = 3
printABC(K)
|
C#
using System;
class GFG {
static void printABC( int K)
{
Console.WriteLine(K + " " + (K + (1 << 27)) + " "
+ 0);
}
public static void Main()
{
int K = 3;
printABC(K);
}
}
|
Javascript
<script>
const printABC = (K) => {
document.write(`${K} ${K + (1 << 27)} ${0}<br/>`);
}
let K = 3;
printABC(K);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...