Luogu P8255 数学游戏 题解
Luogu P8255 数学游戏 题解
题目大意
现有若干正整数 \(x,y,z\) 满足 \(z=x\times y\times\gcd(x,y)\) ,给定 \(z,x\) ,求 \(y\) 。无解输出 \(-1\)
I/O
Input
第一行一个整数,表示有 \(t\) 对正整数 \(x,y\)
接下来 \(t\) 行,每行两个正整数 \(x,z\)
Output
对于每对数字输出一行 \(y\) ,无解输出 \(-1\)
I/O e.g.
Input#1
1
10 240
Output#1
12
Input#2
3
5 30
4 8
11 11
Output#2
6
-1
1
题解
\[\begin{align}
\notag i&)\because\ x,y,z为正整数\\\notag
&\therefore 若x\not{|}\ \ z,无解\\\notag
ii&)\ 若\ x|z\\\notag
&令\ x=a\times d,y=b\times d,其中\gcd(a,b)=1\\\notag
&有\ \gcd(x,y)=d\\\notag
&\therefore\ z=x\times y\times\gcd(x,y)=a\times b\times d^3\\\notag
&\therefore\ \frac zx=b \times d^2\\\notag
&\because\ \gcd(a,b)=1\Rightarrow\ \gcd(a^2,b)=1\\\notag
&\therefore\ \gcd(x^2,\frac zx)=\gcd(a^2d^2,bd^2)=d^2\gcd(a^2,b)=d^2\\\notag
&\therefore\ 若\gcd(x^2,\frac zx)不为完全平方数,无解\\\notag
&\therefore\ \frac{\frac zx}{\sqrt{\gcd(x^2,\frac zx)}}=\frac{b\times d^2}d=bd=y
\end{align}
\]
Code
#include<bits/stdc++.h>
using namespace std;
#define GO(u,v,i) for(register int i=u;i<=v;i++)
template<class t>inline t fr(){
register t num=0,dis=1;
register char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')dis=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){num=(num<<1)+(num<<3)+(ch^48);ch=getchar();}
return num*dis;
}
template<class t>inline void fw(t num){
if(num>9)fw(num/10);
putchar(num%10+'0');
}
template<class t>inline void fw(t num,char ch){
if(num<0)num=-num,putchar('-');
fw(num);putchar(ch);
}
typedef long long lld;
template<class t>inline t gcd(t a,t b){return b==0?a:gcd(b,a%b);}
lld x,z;
lld t;
inline bool check(lld num){
lld ans=(int)sqrt(num);
return num==ans*ans;
}
signed main(){
t=fr<lld>();
GO(1,t,i){
x=fr<lld>(),z=fr<lld>();
if(z%x){
fw(-1,'\n');continue;
}
z/=x;
lld cc=gcd(x*x,z);
if(check(cc)){
lld ans=z/(int)sqrt(cc);
fw(ans,'\n');
}
else fw(-1,'\n');
}
return 0;
}

浙公网安备 33010602011771号