使用 C++ 查找 n = x + n x 的解的个数


在本文中,我们将找到方程 n = x + n ⊕ x 的解的个数,即我们需要找到给定值 n 下可能的 x 值的个数,使得 n = x + n ⊕ x,其中 ⊕ 表示异或运算。

现在我们将讨论有关 n = x + n ⊕ x 的解的个数的完整信息,并提供相应的示例。

暴力方法

我们可以简单地使用暴力方法来查找解的个数,即对于给定的 n 值,我们应用从 0 开始的每个整数 x 值,并验证方程是否满足,x 的值应小于或等于 n,因为将大于 n 的值与 (n ⊕ x) 相加永远不会返回 n 作为答案。

示例

找到 n = 3 的一个 x 值?

   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

示例

#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;
}

输出

Number of possible solutions : 4

这是一个简单的 C++ 程序,用于通过应用暴力方法查找 n = x + n ⊕ x 的解的个数。

有效方法

在这种方法中,如果我们查看二进制形式的 **n**,我们需要找到设置为 1 的位的数量,并且查看方程,我们可以说如果 n 设置,则 x 将设置或 **n** ⊕ x 将设置,因为 1 ⊕ 1 = 0。这意味着 n ⊕ x 没有设置它,因此现在我们可以得出 n 中每个设置位的排列数,即 2^(设置位的数量)。

示例

#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;
}

输出

Number of possible solutions : 4

程序的复杂度

这种方法的时间复杂度为 O(n),因为我们在这里应用了暴力方法。我们可以应用更有效的方法来提高程序的效率。

结论

在本文中,我们解决了一个问题,即查找解的数量 -

n = x + n ⊕ x。我们还学习了此问题的 C++ 程序以及我们解决此问题的完整方法。我们可以用其他语言(如 C、Java、Python 和其他语言)编写相同的程序。希望本文对您有所帮助。

更新于: 2021-11-24

180 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.