码迷,mamicode.com
首页 > 其他好文 > 详细

A Simple Problem

时间:2020-05-25 19:26:17      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:tin   lse   namespace   ret   min   simple   展开   first   instead   

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

把这个式子移项,然后用平方差展开。
就会发现:(y-x)(y+x)=n

Code

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int main(){
    //freopen("1.in","r",stdin);
    int t;scanf("%d",&t);
    while(t--){
        int n;scanf("%d",&n);
        int ans=0x3f3f3f3f;
        for(int i=1;i*i<=n;i++){
            if(n%i==0){
                int x=i,y=n/i;
                int now=y-x;
                //printf("%d\n",now);
                if(now%2)continue;
                if(now!=0)ans=min(ans,now/2);
            }
        }
        if(ans==0x3f3f3f3f)printf("-1\n");
        else printf("%d\n",ans);    
    }
    return 0;
}

A Simple Problem

标签:tin   lse   namespace   ret   min   simple   展开   first   instead   

原文地址:https://www.cnblogs.com/Lour688/p/12958474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!