您的位置:首页 > 其它

hdu 4143(分解质因数)

2016-01-27 10:23 246 查看

A Simple Problem

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


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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).

 

[align=left]Output[/align]
For each integer n, please print output the x in a single line, if x does not exit , print -1 instead.
 

[align=left]Sample Input[/align]

2
2
3

 

[align=left]Sample Output[/align]

-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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数学