Fraction Construction Problem

Fraction Construction Problem

参考:
https://blog.csdn.net/bbbll123/article/details/107451028
https://blog.csdn.net/qq_43054573/article/details/107443839

#pragma GCC optimize(3,"Ofast","inline")
#include
using namespace std;
typedef long long ll;
typedef pairP;
const int inf = 0x7f7f7f7f;
const int N = 2e6+10;
const ll mod = 1e9+7;
const double PI = 3.14;

inline int read(){
    char ch=getchar();int x=0,f=1;
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline int random(int n){return(ll)rand()*rand()%n;}


inline void exgcd(int a,int b,ll &x,ll &y){
    if(b == 0){
        x = 1;y = 0;
        return;
    }
    exgcd(b,a%b,y,x);
    y -= a/b*x;
}


int gcd(int n,int m){
    int r = n%m;
    while(r){
        n = m;
        m = r;
        r = n%m;
    }
    return m;
}

inline void solve(){
    int c,d,e,f;
    int a = read(),b = read();
    if(b <= 1){
        puts("-1 -1 -1 -1");
        return;
    }
    int g = gcd(a,b);
    if(g != 1){
        c = a/g;d = b/g;f = d;e = 1;c++;
        printf("%d %d %d %d\n",c,d,e,f);
        return;
    }
    f = 0,d = 0;
    for(int i = 2;i*i <= b;i++){
        if(b%i == 0 && gcd(i,b/i) == 1ll && i < b && b/i < b){
            f = i;
            d = b/i;
            break;
        }
    }
    if(f+d == 0){
        puts("-1 -1 -1 -1");
        return;
    }

    ll x,y;
    exgcd(f,d,x,y);//x = c,y = e
    x *= (ll)a;
    y *= (ll)a;
    if(x > 0 &&y < 0){
        printf("%lld %d %lld %d\n",x,d,-y,f);
    }else {
        printf("%lld %d %lld %d\n",y,f,-x,d);
    }
}
int main(){
    //srand((unsigned)time(0));
    //freopen("out.txt","w",stdout);
    //freopen("in.txt","r",stdin);
    int t = read();
    while(t--){
        solve();
    }
    return 0;
}

你可能感兴趣的:(牛客,扩展欧几里得)