A very hard mathematic problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8579 Accepted Submission(s): 2624
Problem Description
Haoren is very good at solving mathematic problems. Today he is working a problem like this:
Find three positive integers X, Y and Z (X < Y, Z > 1) that holds
X^Z + Y^Z + XYZ = K
where K is another given integer.
Here the operator “^” means power, e.g., 2^3 = 2 * 2 * 2.
Finding a solution is quite easy to Haoren. Now he wants to challenge more: What’s the total number of different solutions?
Surprisingly, he is unable to solve this one. It seems that it’s really a very hard mathematic problem.
Now, it’s your turn.
Input
There are multiple test cases.
For each case, there is only one integer K (0 < K < 2^31) in a line.
K = 0 implies the end of input.
Output
Output the total number of solutions in a line for each test case.
Sample Input
9 53 6 0
Sample Output
1 1 0
Hint
9 = 1^2 + 2^2 + 1 * 2 * 2 53 = 2^3 + 3^3 + 2 * 3 * 3
题意:给你一个数k(k<=1e9),让你找满足x^z+y^z+xyz=k(x^k为x的k次方,x>0,x<y,z>1)的解x,y,z有多少组。
思路:
由于关键条件z>1,所以x和y都不会超过sqrt(k)。
因此可以暴力枚举x和z,然后二分y的值。
但是直接这样会TLE。一想到剪枝,首先pow可以扔个快速幂上去。。。
考虑到0<x<y,也就是说,y至少为2,即z最大为2^z不大于k的最大的数。
x的限制就简单了,确定z以后,x^z不大于k。由于x<y,因此其实x^z>k/2就可以break了。
然后l=x+1,r=k,二分一下y,累加答案。
这个时候你会惊奇的发现
居然是WA???
为什么呢???
k的范围为1e9,z最大为30,你二分判断的时候算的是x^z+mid^z+x*mid*z
mid的z次方? 你确定不会爆long long?
说实话,这个问题我一直没有发现,直到最后WA到绝望,看了题解,才惊觉此事。真的没想到WA居然是因为r设置的太大了。。。
那怎么设置r呢?
考虑到y^z也是<k的,我们可以取r=z次根号下k,也就是k的1/z次方,这样就不会爆精度了。(事实证明sqrt(k)也会爆)
最后顺利AC。
代码:
#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<map>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=200010;
ll n,m,k;
int a[maxn],ans;
ll power(ll a,ll n) //a的n次方mod
{
ll ans=1;
while (n)
{
if(n&1) ans=(ans*a);
n>>=1;
a=(a*a);
}
return ans;
}
ll jud(ll x,ll y,ll z)
{
return power(x,z)+power(y,z)+x*y*z;
}
int main()
{
while(scanf("%lld",&n)!=EOF&&n)
{
ll up=1,cnt=0;
while(up<n){cnt++;up<<=1;}
ll ans=0;
for(ll z=2;z<=cnt;z++)
{
for(ll x=1;;x++)
{
ll xx=power(x,z);
if(xx>n/2) break;
ll l=x+1,r=(ll)pow((double)n,1.0/(double)z)+1;
while(l<r)
{
ll mid=(l+r)/2;
ll kk=jud(x,mid,z);
if(kk==n) {ans++;break;}
else if(kk>n) r=mid;
else l=mid+1;
}
}
}
printf("%lld\n",ans);
}
return 0;
}