F. Fraction Construction Problem (扩展欧几里得) 2020牛客暑期多校训练营(第三场)

传送门

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
思路:

  • 若a 与 b不互质,那么令 e / f = 1,则可求得c =(a + b) / gcd(a,b) 且d = b / gcd(a,b) e = 1,f = 1。
  • 可令df = b,且让d与f互质,直接用扩展欧几里得来做就行了。
  • 详细代码思路也可见大佬博客

代码实现:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e6 + 5;

int t, a, b;
int c, d, e, f;

ll exgcd(ll a,ll b,ll &x1,ll &y1){
	if(!b){
		x1 = 1; y1 = 0;
		return a;
	}
	int g = exgcd(b,a%b,x1,y1);
	int tmp = x1; x1 = y1;
	y1 = tmp-(a/b)*y1;
	return g;
}

vector<int> vt;
int factor[N], vis[N];

void divide(int n){
	me(vis);
	for(int i = 2; i < n; i ++){
		if(!vis[i]){
			vt.push_back(i);
			factor[i] = i;
		}
		for(int j = 0; j < vt.size() && i * vt[j] < n; j ++){
			vis[i * vt[j]] = 1;
			factor[i * vt[j]] = vt[j];
			if(i % vt[j] == 0) break;
		}
	}
}



signed main()
{
    IOS;
    divide(N);
    cin >> t;
    while(t --){
        cin >> a >> b;
        if(b == 1){
            cout << "-1 -1 -1 -1" << endl;
            continue;
        }
        int g = __gcd(a, b);
        if(g != 1){
            cout << (a + b) / g << " " << b / g << " 1 1" <<endl;
            continue;
        }
        int fc = factor[b];
        d = 1; f = b;
        while(f % fc == 0) d *= fc, f /= fc;
        if(f == 1){
            cout << "-1 -1 -1 -1" << endl;
            continue;
        }
        exgcd(d, f, c, e);
        c = -c;
        while(c <= 0 || e <= 0) c += f, e += d;
        c *= a, e *= a;
        cout << e << " " << d << " " << c << " " << f << endl;
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/107570434