输入格式:
输入在一行中给出一个正整数 n(2<n<231)。
输出格式:
如果 n 是大幂数,则在一行中输出幂次最大的那个和,格式为:
1^k+2^k+...+m^k
其中 k
是所有幂次和中最大的幂次。如果解不存在,则在一行中输出 Impossible for n.
,其中 n
是输入的 n 的值。
输入样例 1:
91
输出样例 1:
1^2+2^2+3^2+4^2+5^2+6^2
输入样例 2:
2147483647
输出样例 2:
Impossible for 2147483647.
思路:
确定幂的最大值,然后从小到大枚举,再用快速幂优化。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// 快速幂算法
ll qmi(ll m, ll k)
{
ll res = 1, t = m;
while (k)
{
if (k & 1) res = res * t;
t = t * t;
k >>= 1;
}
return res;
}
ll n, mi, pos;
bool found = false;
void fun(ll k)
{
ll sum = 0;
for (ll i = 1; ; i++)
{
ll term = qmi(i, k);
sum += term;
if (sum > n)
break;
if (sum == n)
{
mi = k;
pos = i;
found = true;
break;
}
}
}
int main()
{
cin >> n;
// 动态确定幂次上限
int maxPower = log2(n) + 1;
for (int k = maxPower; k >= 1; k--)
{
if (found)
break;
fun(k);
}
if (found)
{
for (int i = 1; i <= pos; i++)
{
if (i > 1)
cout << "+";
cout << i << "^" << mi;
}
}
else
{
cout << "Impossible for " << n << ".";
}
return 0;
}