Find the Number of Solutions of n = x + n x using C++

C++Server Side ProgrammingProgramming

In this article we are going to find number of solution of equation n = x + n ⊕ x, i.e we need to find number of values of x possible with given value n such that n = x + n ⊕ x where ⊕ represents XOR operation.

Now we will discuss the complete information regarding number of solutions of n = x + n ⊕ x with an appropriate examples.

Brute Force Method

We can simple use brute force approach in order to find number of solution, i.e for given value of n we apply every integer value of x starting from 0 and verify whether the equation satisfies or not, value of x should be less than or equals to n because adding value greater than n with (n ⊕ x) will never return n as answer.

Example

Find one value of x for n = 3?

   n = x + n ⊕ x
Putting x = 0,
   3 = 0 + 3 ⊕ 0
3 ⊕ 0 = 3,
   3 = 3
   LHS = RHS(x = 0 satisfy the equation)
So, x = 0 is one of the solution

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n = 3, c=0;
    for (int x = 0; x <= n; ++x)// loop for giving value of x from 0 to n
        if (n == x + n ^ x)//checking if value of x satisfies the equation
            ++c;
    cout  << "Number of possible solutions : " << c;
    return 0;
}

Output

Number of possible solutions : 4

This is simple C++ program to find number of solutions of n = x + n ⊕ x by applying Brute force method.

Efficient Approach

In this approach, if we look at n in the binary form, we need to find the number of bits that are set to 1, and looking at the equation, we can say if n is set, then either x will be set or n ⊕ x will be set because 1 ⊕ 1 = 0. It means that n ⊕ x doesn't have it set, so now we can conclude the number of permutations for every set bit in n, i.e., 2^(number of set bits).

Example

#include <bits/stdc++.h>
using namespace std;
int main (){
    int n = 3, no_of_setbits = 0;    // initialising n with value and taking count of set bits as 0
    while (n != 0){
        no_of_setbits = no_of_setbits + (n % 2);    // checking if num contains set bit.
        n = n / 2;
    }
    int result = 1 << no_of_setbits;    // calculating no. of possible solution with 2^setbits
    cout << " Number of possible solutions : " << result;
    return 0;
}

Output

Number of possible solutions : 4

Complexity of Program

The time complexity of this approach is O(n), as we are applying Brute force here. We can apply more efficient methods to improve the efficiency of the program.

Conclusion

In this article, we solve a problem to find a number of solution −

n = x + n ⊕ x. We also learned the C++ program for this problem and the complete approach by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.

raja
Published on 24-Nov-2021 12:09:50
Advertisements