hdu 4143(分解质因数)

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值