HDU 2092
有二個整數,它們加起來等於某個整數,乘起來又等於另一個整數,它們到底是真還是假,也就是這種整數到底存不存在,實在有點吃不準,你能快速回答嗎?看來只能通過編程。
例如:
x + y = 9,x * y = 15 ? 找不到這樣的整數x和y
1+4=5,1*4=4,所以,加起來等於5,乘起來等於4的二個整數爲1和4
7+(-8)=-1,7*(-8)=-56,所以,加起來等於-1,乘起來等於-56的二個整數爲7和-8
Output只需要對於每個n和m,輸出“Yes”或者“No”,明確有還是沒有這種整數就行了。
Sample Input
9 15 5 4 1 -56 0 0Sample Output
No Yes Yes
這個題算是利用數學的典型題目吧,一開始想的滿腦子都是暴力與優化,後來直接發現用數學解法特別簡單。
由於數據量是-10000到10000,所以暴力是可以的。遍歷其積的因子從1到平方根,每一次判斷其是否有解即可。
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int main()
{
int a,b;
while(cin>>a>>b && (a||b))
{
int bb = abs(b);
if(bb==0)
{
cout<<"Yes"<<endl;
continue;
}
int uper=sqrt(bb);
int yes=0;
for(int i=1;i<=uper;i++){
if(bb%i==0){
if(b>0){
if(i+bb/i==a || -i-bb/i==a)
{
yes=1;
break;
}
}
else
{
if(-i+bb/i==a || i-bb/i==a)
{
yes=1;
break;
}
}
}
}
if(yes)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
int a,b;
while (cin>>a>>b && (a||b)){
int aa = a*a;
int bb = 4*b;
int cc = sqrt(aa-bb);
if(aa-bb>=0 && aa-bb == cc*cc)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}