用其他數的冪表示數字的 C++ 表示


討論用另一個數的冪表示一個數的問題。給定兩個數 x 和 y,我們需要判斷 y 是否可以用 x 的冪表示,其中 x 的每個冪只能使用一次,例如

Input: x = 4, y = 11
Output: true
Explanation: 4^2 - 4^1 - 4^0 = 11 Hence y can be represented in the power of x.

Input: x = 2, y = 19
Output: true
Explanation: 2^4 + 2^1 + 2^0 =19 Hence y can be represented in the power of x.

Input: x = 3, y = 14
Output: false
Explanation: 14 can be represented as 3^2 + 3^1 + 3^0 + 3^0 but we cannot use one term of power of x twice.

尋找解決方案的方法

從如何用 2 的冪表示 19 的例子中,我們可以形成一個方程:

c0(x^0) + c1(x^1) + c2(x^2) + c3(x^3) + … = y ….(1),

其中 c0、c1、c2 可以是 -1、0、+1,分別表示減去 (-1) 項、加上 (+1) 項或不包含 (0) 項:

c1(x^1) + c2(x^2) + c3(x^3) + … = y - c0,

將 x 作為公因數提出:

c1(x^0) + c2(x^1) + c3(x^2) + … = (y - c0)/x ….(2),

從等式 (1) 和 (2) 中,我們可以再次用這種方式表示這個數,並且為了存在解,(y - Ci) 應該能被 x 整除,而 Ci 只能包含 -1、0 和 +1。

所以最終我們需要檢查直到 y>0 是否 [(y-1) % x == 0] 或 [(y) % x == 0] 或 [(y+1) % x == 0],或者是否存在解。

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
   int x = 2, y = 19;
   // checking y divisibility till y>0
   while (y>0) {
      // If y-1 is divisible by x.
      if ((y - 1) % x == 0)
         y = (y - 1) / x;
        // If y is divisible by x.
      else if (y % x == 0)
         y = y / x;
         // If y+1 is divisible by x.
      else if ((y + 1) % x == 0)
         y = (y + 1) / x;
         // If no condition satisfies means
         // y cannot be represented in terms of power of x.
      else
         break;
   }
   if(y==0)
      cout<<"y can be represented in terms of the power of x.";
   else
      cout<<"y cannot be represented in terms of the power of x.";
   return 0;
}

輸出

y can be represented in terms of the power of x.

結論

在本教程中,我們討論瞭如何檢查一個數是否可以用另一個數的冪來表示。我們討論了一種簡單的解決方法,透過檢查當前數、前一個數和後一個數能否被 y 整除。

我們還討論了這個問題的 C++ 程式,我們也可以用 C、Java、Python 等程式語言來實現。希望本教程對您有所幫助。

更新於:2021年11月26日

192 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告