HDU - 4143 A Simple Problem 题解

E - A Simple Problem

HDU - 4143

题目描述

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

分析

一句话题意:给定n,求最小的正整数x,使得 n+x^2也是完全平方数。

因为\(x^{2}+n=y^{2}\),所以就有\(y^{2}-x^{2}=n\)

然后我们根据平方差公式分解因式\((y+x)(y-x)=n\)

这样我们只需要从1到\(\sqrt{n}\)枚举n的约数就可以了

如果n%i=0,那么就有\(y+x=n/i\)

\(y-x=i\)

两式相减,得\(x=\frac{n/i-i}{2}\)

最后注意x不能为小数并且x要大于0就可以了

代码

#include<bits/stdc++.h>
using namespace std;
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int n;
		scanf("%d",&n);
		int xx=0x3f3f3f3f;
		for(int i=1;i*i<=n;i++){
			if(n%i==0){
				int lef=i,rig=n/i;
				if((rig-lef)%2) continue;
				if((rig-lef)/2!=0)xx=min(xx,(rig-lef)/2);
			}
		}
		if(xx==0x3f3f3f3f) printf("-1\n");
		else printf("%d\n",xx);
	}
	return 0;
}
posted @ 2020-05-24 14:16  liuchanglc  阅读(174)  评论(0编辑  收藏  举报