0
点赞
收藏
分享

微信扫一扫

hdu 4143(分解质因数)

小黑Neo 2023-05-29 阅读 76


A Simple Problem


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)



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


 


我的思路:首先这个题目的数据量达到了10^9,穷举肯定会爆掉,但是如果我把等式变下形,(y+x)*(y-x)= n,那么接下来只要把n分解成a*b=n的形式就ok了。这里的分解就类似于素数打表的方法。。。因为y没有说明正负,所以有负数的情况,但是TLE了。。。


#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;

const int inf = 1e9;
int main()
{	
	int t,n;
	cin>>t;
	while(t--)
	{
		cin>>n;
		int x = inf,q = sqrt(n+0.5);
		for(int i = -q; i <= q; i++)
		{
			if(i == 0) continue;
			if(n % i == 0)
			{
				int j = n / i;
				if(i > j)
					swap(i,j);
				if((i + j) % 2 == 0 && (j - i) % 2 == 0)
				{
					x = min(x,(j - i) / 2);
				}
			}
		}
		if(x == inf || x <= 0) cout<<-1<<endl;
		else cout<<x<<endl;
	}
	return 0;
}





n = ( y - x )*( y + x ) ;令 y - x = i,所以有 x + y = n / i ,即 ( n / i - i ) / 2 = x.

注意:x 要大于 0 ,当 n 是完全平方数时要注意。

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;

int main()
{
    int t,i,n;
    cin>>t;
    while(t--)
    {
       cin>>n;
       for(i=sqrt(n);i>0;i--)
       {
          if(n%i==0&&(n/i-i)%2==0&&n/i!=i)
          {
              cout<<(n/i-i)/2<<endl;
              break;
          }
       }
       if(i==0) cout<<-1<<endl;
    }
    return 0;
}




举报

相关推荐

0 条评论