J. 邬澄瑶的公约数 (多个指数的gcd & map.count()) (2021牛客寒假算法基础集训营4)

传送门

思路:

在求多个数的gcd时无非就是分解质因数,那么对于这个题我们就需要分解n个指数 x_{i}^{p_{i}} 的质因数,并找到其公共的质因数 y和它的最小指数w,答案就是所有y^{w}的乘积。

例如:gcd(24,32,36) = gcd(2^{3} * 3,2^{4}2^{2} * 3^{2}),共同的质因数为2,分别出现了 3, 4, 2 次,最小出现次数就为 2,因此gcd(24, 32, 36) = 2^{2} =4.

代码实现:

#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 = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9+7;
const int  N = 2e5 + 5;

inline void read(int &x){
    char t=getchar();
    while(!isdigit(t)) t=getchar();
    for(x=t^48,t=getchar();isdigit(t);t=getchar()) x=x*10+(t^48);
}


int qmi(int a, int k)
{
    int res = 1;
    while(k){
        if(k & 1) res = (ll)res * a % mod;
        k >>= 1;
        a = (ll)a * a % mod;
    }
    return res;
}

int n, x[N], p[N];
vector<int> v;
unordered_map<int, int> mp, ct;

signed main()
{
    IOS;
    cin >> n;
    for(int i = 0; i < n; i ++) cin >> x[i];
    for (int i = 0; i < n; i++) cin >> p[i];
    for(int i = 0; i < n; i ++){
        int pre = x[i];
        for(int j = 2; j <= pre/j; j ++){ //进行质因数分解
            if(pre%j==0){
                mp[j] ++; //统计质因数j出现的次数
                int cnt = 0;
                while(pre%j==0){
                    pre /= j;
                    cnt ++;
                }
                cnt *= p[i];
                if(!ct.count(j)) ct[j] = cnt; //更新质因数j在每个数中出现的最小次数
                else ct[j] = min(ct[j], cnt);
            }
        }
        if(pre>1){
            mp[pre] ++;
            if(!ct.count(pre)) ct[pre] = p[i];
            else ct[pre] = min(ct[pre], p[i]);
        }
    }
    for(auto &u:mp)
        if(u.second==n)  //如果这个质因数出现了n次
            v.push_back(u.first);
    int ans = 1;
    for(auto &u:v) ans = ans*qmi(u, ct[u])%mod; //答案就是所有出现n次质因数与其最小次数的乘积
    cout << ans << endl;

    return 0;
}

猜你喜欢

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