Count distinct XOR values among pairs using numbers in range 1 to N
Given a number N. The task is to count the number of distinct XOR of any possible pairs using numbers from 1 to N inclusive.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: N = 3
Output: 4
Explanation: Following are the all possible pairs using elements from 1 to N inclusive.
1^1 = 0
1^2 = 3
1^3 = 2
2^2 = 0
2^3 = 1
3^3 = 0
Therefore, there are 4 distinct possible XOR values.Input: N = 2
Output: 2
Approach: This problem is observation-based. Follow the steps below to solve the given problem.
- For N = 1 and N = 2 the require output are 1 and 2 respectively.
- Now for N≥3, there are two possible cases:
- If N is not a power of two then, there will be a total of ‘t’ numbers where t is the power of 2 which is just next to the number N. They vary from [0 to t – 1]. Because let’s say, N = 5 or 6 or 7 In all the above cases values varies from [0, 1, 2, 3, 4, 5, 6, 7].
- If N is a power of two then, all the numbers will be possible except the number itself. Because let’s say, N = 4 in binary it is “100” so as we know XOR operation gives “1″ if both bits are different else it gives 0. Possible values are [0, 1, 2, 3,
4, 5, 6, 7].
Below is the implementation of the above approach.
C++
// C++ code to implement above approach#include <cmath>#include <iostream>using namespace std; int findDistinctXOR(int n){ // Corner case if (n == 1) { cout << 1 << endl; } if (n == 2) { cout << 2 << endl; } long long x, next; x = log2(n); // if n is power of two if ((n & (n - 1)) == 0) { next = pow(2, x + 1); cout << next - 1 << endl; } else { next = pow(2, x + 1); cout << next << endl; }} // Driver Codeint main(){ int N = 3; findDistinctXOR(N); return 0;} |
4
Time Complexity: O(1)
Auxiliary Space: O(1)

