数字游戏

· · 个人记录

P8255

这是一道纯数学题。
题目给出x,z,请求最小的y,使得:

z = x \times y \times gcd(x,y)

或判断无解(当然,本题做法少有的与数据范围无关)

首先,这个式子是动不了的,那么就将其中一些数拆分
突然注意到:gcd(x,y)很难拆得动,但x,y很容易拆成关于gcd的因式,于是考虑:
设 gcd(x,y) = d, x = a \times d, y = b \times d 则 a \perp b

\text{于是} z &= abd^3 \\ \frac{z}{x} &= bd^2 \\ \text{再次注意到} gcd( \frac{x}{z}, x^2) &= gcd(bd^2,a^2d^2)\\ &= d^2gcd(b,a^2)\\ &= d^2\\ 则有gcd( \frac{x}{z},x^2) &= gcd(x,y)^2 \\ \text{得到} y &= \frac{ \frac{z}{x}}{gcd(x,y)} \\ &= \frac{ \frac{z}{x}}{ \sqrt{gcd( \frac{z}{x}, x^2)}} \end{aligned}

在推理过程中,只有两个地方可能不是整数: \frac{z}{x}, \sqrt{gcd(\frac{z}{x},x^2)}
只需要判断一下这两个数是否是整数即可
注意:判断开根时要四舍五入,即+0.5以后再下取整

Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int T; 
ll x,z;
ll gcd(ll a,ll b){
    if(b == 0) return a;
    return gcd(b,a%b);
}/*
bool check(ll a){
    for(int i=1;i<=sqrt())
}*/
signed main(){
    freopen("math4.in","r",stdin);
    freopen("math4.ans","w",stdout);
    cin>>T;
    while(T--){
        cin>>x>>z;
        if(z%x){
            cout<<-1<<"\n";
            continue;
        }
        ll d = (z/x>x*x) ? gcd( z/x, x*x) : gcd(x*x,z/x);
        ll op = (ll)(sqrt(d*1.0) + 0.5);
        if( op*op == d ){
            cout<< (z/x)/op <<"\n";
        }else cout<<-1<<"\n";
    }
    return 0;
}