The Wayback Machine - https://web.archive.org/web/20220327022919/https://www.geeksforgeeks.org/find-triplet-a-b-c-having-bitwise-and-of-bitwise-or-with-each-other-as-k/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find triplet A, B, C having bitwise AND of bitwise OR with each other as K

  • Last Updated : 25 Mar, 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++




// C++ program to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print three integers
void printABC(int K)
{
 
    // One of them are equal to zero
    // and rest two are equivalent
    // to X itself but to make
    // A!=B add a larger power of 2 to B
    cout << K << " " << K + (1 << 27)
         << " " << 0 << endl;
}
 
// Driver Code
int main()
{
    int K = 3;
 
    // Function call
    printABC(K);
    return 0;
}

Javascript




<script>
    // JavaScript program to implement the approach
 
    // Function to print three integers
    const printABC = (K) => {
 
        // One of them are equal to zero
        // and rest two are equivalent
        // to X itself but to make
        // A!=B add a larger power of 2 to B
        document.write(`${K} ${K + (1 << 27)} ${0}<br/>`);
    }
 
    // Driver Code
    let K = 3;
 
    // Function call
    printABC(K);
 
// This code is contributed by rakeshsahni
 
</script>
Output
3 134217731 0

Time Complexity: O(1)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!