Hdoj 4143 A Simple Problem

来源:互联网 发布:java 9 编辑:程序博客网 时间:2024/06/05 19:14
Problem DescriptionFor 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.InputThe 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).OutputFor each integer n, please print output the x in a single line, if x does not exit , print -1 instead.Sample Input223Sample Output-11AuthorHITSource2011百校联动“菜鸟杯”程序设计公开赛 

题目分析
重点内容 y^2=n+x^2 → (y+x)(y-x)=n → x=(n/i-i)/2;
讲y-x视为i,枚举i即可,同时要求最小解,则i从sqrt(n)(由基本不等式可以得到sqrt(n)为有可能的最大的值)枚举到1,理由是x越小则y+x和y-x的差值越小

Code

#include<iostream>#include<cstdio>#include<algorithm>#include<cmath>#include<cctype>#include<cstring>#include<cstdlib>using namespace std;int main() {    int t,n;    cin>>t;    while(t--)    {        cin>>n;        int k=sqrt(n);        bool flag=false; //判读是否有找到        for(int i=k;i>=1;i--)        {            if( (n/i-i)%2==0 && n%i==0 && n/i!=i )             {                cout<<(n/i-i)/2;                flag=true;                break;            }        }        if(!flag) cout<<-1;        cout<<endl;    }}

更多问题请关注个人博客,不定时更新

原创粉丝点击