题意:
给定$a, b, c, d$,求$x$满足$gcd(a, x) = b$且$lcm(c, x) = d$
思路:
枚举d的所有约数,判断每个数是否满足条件。(直接枚举会超时)
优化:枚举质数(相当于d质因子分解),$dfs$枚举所有约数,判断是否满足条件
Code:
#include <map> #include <vector> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; ll a, b, c, d, x; vector <pair<int, int>> v; map <ll, bool> mp; void dfs(int cnt, ll res){ if(!mp[res] && __gcd(a, res)== b && c / __gcd(c, res) * res == d){ x ++; mp[res] = true; } if(cnt == (int)v.size()) return; int p = v[cnt].first, k = v[cnt].second; ll mid = 1; for(int i = 0; i <= k; i ++){ dfs(cnt + 1, res * mid); mid *= p; } } int main(){ int n; scanf("%d", &n); while(n --){ x = 0; scanf("%lld%lld%lld%lld", &a, &b, &c, &d); v.clear(); mp.clear(); ll k = d; for(int i = 2; i <= k / i; i ++){ if(k % i == 0){ int s = 0; while(k % i == 0){ s ++; k /= i; } v.push_back({i, s}); } } if(k > 1) v.push_back({k, 1}); dfs(0, 1); cout << x << endl; } return 0; }