题目链接
http://acm.split.hdu.edu.cn/showproblem.php?pid=4143
A Simple Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 5326 Accepted Submission(s): 1385
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).
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
Author
HIT
Source
Recommend
对题中算式进行化简为:n=(x+y)*(x-y),设i=x+y,则y=(i+j)/2,x=y-i
x+y=n/i和x=y-i联立,消去y,则x=[(n/i)-i]/2
这样二重循环降到遍历一次,当y=0时,x^2=n,所以上限为n的算数平方根。再根据x>0,进行优化
还有一个容易忽视的地方,x为最小正整数,所以遍历从大到小
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main(){
int T;
int n,i,j,k,x,y;
int ans;
scanf("%d",&T);
while(T--){
ans=-1;
scanf("%d",&n);
for(i=sqrt(n);i>0;i--){
if(n%i==0&&(n/i-i)%2==0&&(n/i-i)/2>0){///确保x为整数,并且为正数
ans=(n/i-i)/2;
break;
}
}
printf("%d\n",ans);
}
return 0;
}