C - A very hard mathematic problem

xiaoxiao2021-02-28  68

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 0Sample Output 1 1 0    Hint

9 = 1^2 + 2^2 + 1 * 2 * 2 53 = 2^3 + 3^3 + 2 * 3 * 3

    思路:充分利用题目中的条件,0<x<y  说明y最小的是2,所以进一步可以知道z最大的也只能是31,然后进行枚举z,枚举x,因                为要用到二分法,所以要将y 的最大值确定下来,也就是的=( int) pow( double (n), 1.0/( double) z);      注意:因为,为                 了避免超时,在这里我采用了快速幂的算法,还有为了避免某些数的溢出我用了long long ;

#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; long long fun(long long a,long long b){     long long  sum= 1,z=a;     while(b)     {         if(b% 2) sum*=z;         z=z*z;         b/= 2;     }     return sum; } ///X^Z + Y^Z + XYZ = K int main(){     int n;     while( scanf( "%d",&n)== 1)     {         if(n== 0)             break;         int Z= 0,sum= 0;         long long y;         for( y= 2; y<=n; y=y* 2)             Z++;         int k= sqrt(n);         if(k*k==n) //z等于2 的情况             sum=(k -1)/ 2;         for( int z= 3; z<=Z; z++)         {             for( int x= 1; ; x++)             {                 long long  al=fun(x,z);                 if(al>n/ 2) break; //y总是大于x,所以x^z总是小于n/2;                 int q=x+ 1, w=( int) pow( double (n), 1.0/( double) z);                 while(q<=w)                 {                     y=(q+w)/ 2;                     if(al+fun(y,z)+z*x*y>n)                         w=y -1;                     else if(al+fun(y,z)+z*x*y<n)                         q=y+ 1;                     else                     {                         sum++;                         break;                     }                 }             }         }         printf( "%d\n",sum);     }     return 0; }
转载请注明原文地址: https://www.6miu.com/read-2630909.html

最新回复(0)