hdu4143 A Simple Problem

时间:2023-03-09 04:31:34
hdu4143  A Simple Problem

A Simple Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 5748    Accepted Submission(s): 1515

Problem Description
For a given positive integer n, please find the smallest positive integer x that we can find an integer y such that y^2 = n +x^2.
Input
The first line is an integer T, which is the the number of cases.
Then T line followed each containing an integer n (1<=n <= 10^9).
Output
For each integer n, please print output the x in a single line, if x does not exit , print -1 instead.
Sample Input
2
2
3
Sample Output
-1
1

// y^2 = n +x^2.即 (y+x)(y-x) = n
//设 i = y-x, n/i = y+x , x = (n/k-k)%2 由于 x, y是正整数, 则 y,x不会等于0, 所以这边还有一点最重要的(y+x) (y-x) 不能相等

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

int main()
{
  int t, n, i, flag, x;
  cin >> t;
  while(t--)
  {
    cin >> n;
    flag = 0;
    i = sqrt(n);
    for(int k = i; k >=1; k--) //题意是求符合条件,最小的x, 所以 k 要从最大因子开始判断
    {
      if(n%k == 0 && (n/k-k)%2 == 0 && n/k != k) //控制好符合条件是最重要的
      {
        x = (n/k - k)/2;
        cout << x << endl;
        flag = 1;
        break;
      }
    }
    if(flag == 0)
    {
      cout << -1 << endl;
    }
  }
  return 0;
}