您的位置:首页 > 其它

hdu 4143 A Simple Problem(数学)

2017-04-23 14:40 399 查看
题目链接

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


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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).

 

[align=left]Output[/align]
For each integer n, please print output the x in a single line, if x does not exit , print -1 instead.
 

[align=left]Sample Input[/align]

2
2
3

 

[align=left]Sample Output[/align]

-1
1

 

[align=left]Author[/align]
HIT
 

[align=left]Source[/align]
2011百校联动“菜鸟杯”程序设计公开赛
 

[align=left]Recommend[/align]
lcy   |   We have carefully selected several similar problems for you:  4144 4147 4145 4146 4148 
 

严格来说不算是一道数学题,主要在于因子化简的思路,避免暴力答案超时

对题中算式进行化简为: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: