当前位置: 代码迷 >> 综合 >> hdu 4143 A Simple Problem(数学)
  详细解决方案

hdu 4143 A Simple Problem(数学)

热度:64   发布时间:2024-01-21 01:46:28.0

题目链接

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).

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
2011百校联动“菜鸟杯”程序设计公开赛

Recommend
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;
}


  相关解决方案