给定两个数字w和m,我们需要确定是否有可能用w的幂表示m。可以将w的幂相加或减去以获得m,而w的每个幂只能使用一次。
例子:
Input : 3 7
Output : Yes
As 7 = 9 - 3 + 1 (3^2 - 3^1 + 3^0 )
so it is possible .
Input : 100 50
Output : No
As 50 is less than 100 so we can never
represent it in the powers of 100 .
在这里,我们必须用仅使用一次的w的幂来表示m,以便可以通过以下等式表示它。
c0 + c1 * w ^ 1 + c2 * w ^ 2 +…= m-(等式1)
其中每个c0,c1,c2…分别为-1 (用于减去w的幂), 0 (不使用w的幂), 1 (用于加w的幂)。
=> c1 * w ^ 1 + c2 * w ^ 2 +…= m – c0
=> w(c1 + c2 * w ^ 1 + c3 * w ^ 2 +…)= m – c0
=> c1 + c2 * w ^ 1 + c3 * w ^ 2 +…=(m – c0)/ w-(等式2)
现在,请注意方程式1和方程式2-我们正在尝试再次解决同一问题。因此,我们必须递归直到m> 0。为了使这种解决方案存在(m_ci)必须是w的倍数,其中ci是方程式的系数。 ci可以为-1,0,1。因此,我们必须检查所有三种可能性((m – 1)%w == 0),((m + 1)%w == 0)和(m%w == 0) 。如果不是,那么将没有任何解决方案。
C++
// CPP program to check if m can be represented
// as powers of w.
#include
using namespace std;
bool asPowerSum(int w, int m)
{
while (m) {
if ((m - 1) % w == 0)
m = (m - 1) / w;
else if ((m + 1) % w == 0)
m = (m + 1) / w;
else if (m % w == 0)
m = m / w;
else
break; // None of 3 worked.
}
// If m is not zero means, it can't be
// represented in terms of powers of w.
return (m == 0);
}
// Driver code
int main()
{
int w = 3, m = 7;
if (asPowerSum(w, m))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
// Java program to check if m can
// be represented as powers of w.
class GFG
{
static boolean asPowerSum(int w, int m)
{
while (m > 0)
{
if ((m - 1) % w == 0)
m = (m - 1) / w;
else if ((m + 1) % w == 0)
m = (m + 1) / w;
else if (m % w == 0)
m = m / w;
else
break; // None of 3 worked.
}
// If m is not zero means, it can't be
// represented in terms of powers of w.
return (m == 0);
}
// Driver function
public static void main (String[] args)
{
int w = 3, m = 7;
if (asPowerSum(w, m))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to check if m can
# be represented as powers of w.
def asPowerSum(w, m):
while (m > 0):
if ((m - 1) % w == 0):
m = (m - 1) / w;
elif ((m + 1) % w == 0):
m = (m + 1) / w;
elif (m % w == 0):
m = m / w;
else:
break; # None of 3 worked.
# If m is not zero means, it can't be
# represented in terms of powers of w.
return (m == 0);
# Driver code
w = 3;
m = 7;
if (asPowerSum(w, m)):
print("Yes");
else:
print("No");
# This code is contributed by mits
C#
// C# program to check if
// m can be represented
// as powers of w.
using System;
class GFG
{
static bool asPowerSum(int w,
int m)
{
while (m > 0)
{
if ((m - 1) % w == 0)
m = (m - 1) / w;
else if ((m + 1) % w == 0)
m = (m + 1) / w;
else if (m % w == 0)
m = m / w;
else
break; // None of 3 worked.
}
// If m is not zero means,
// it can't be represented
// in terms of powers of w.
return (m == 0);
}
// Driver Code
static public void Main ()
{
int w = 3, m = 7;
if (asPowerSum(w, m))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by akt_mit.
PHP
输出:
Yes