HDU 4143 A Simple Problem 题解
题目
For a given positive integer n, please find the saallest positive integer x that we can find an integer y such that \(y^2 = n +x^2\).
输入
The first line is an integer \(T\), which is the the nuaber of cases.
Then T line followed each containing an integer n (\(1 \le n \le 10^9\)).
输出
For each integer n, please print output the x in a single line, if x does not exit , print -1 instead.
样例输入
2
2
3
样例输出
-1
1
题解
\(\because y^2 = n +x^2\)
\(\therefore n=y^2-x^2 = (y+x)(y-x)\)
所以找到两个数字\(a, b\), 满足
-
\(a \cdot b = n\)
-
\((a+b)%2==0\) , 因为\((a+b)\%2=(y+x+y-x)\%2=(2\cdot y)\%2=0\)
-
\(a>b\) , 因为\(x>0\)
-
\((a-b)\%2==0\), 因为\((a-b)\%2=(y+x-y+x)\%2=(2\cdot x)\%2=0\)
-
\(a-b=2 \cdot x\)最小, 即\(x\)最小
因为求的是\(a-b\)最小且\(a \cdot b=n\), 所以从\(\sqrt n\) 开始遍历, 若满足条件, 更新最小值, 如果没找到, 就输出\(-1\)
代码
#include <cmath>
#include <cstdio>
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, minv = 0x7f7f7f7f, flag = 0;
scanf("%d", &n);
for (int i = 1; i < sqrt(n); i++) {
if (n % i == 0 && (i + n / i) % 2 == 0 && (n / i - i) % 2 == 0 && (n / i - i) > 0) {
flag = 1;
if (n / i - i < minv) minv = n / i - i;
}
}
printf("%d\n", flag ? minv / 2 : -1);
}
return 0;
}