使用 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.