h_nosonの日記

競プロ、CTFなど

yukicoder No.368 LCM of K-products

問題
No.368 LCM of K-products - yukicoder
N個の正整数からなる数列A=\{a_1,a_2,...,a_N\}がある.
Aの添字が異なるK個の要素の積からなる集合をBとした時,
Bの全要素の最小公倍数を10^9+7で割った余りを求める.

解法
a=\prod p_i^{a_i},b=\prod p_i^{b_i}(p_i素数)とした時,
最小公倍数は lcm(a,b)=\prod p_i^{\text{max}(a_i,b_i)}となる.
ちなみに最大公約数は gcd(a,b)=\prod p_i^{\text{min}(a_i,b_i)}である.

よって,Bの全要素の最小公倍数は
\text{lcm}(b\in B)=\prod p_i^{\max_{b\in B}(b_i)}
となる.
それぞれのp_iについて指数が最大となるような数をAからK個取り出せばいい.

ソースコード

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

#define RREP(i,s,e) for (i = s; i >= e; i--)
#define rrep(i,n) RREP(i,n-1,0)
#define REP(i,s,e) for (i = s; i < e; i++)
#define rep(i,n) REP(i,0,n)
#define INF 100000000
#define MOD 1000000007

typedef long long ll;

ll power(ll x, int n) {
    ll ret = 1;
    while (n > 0) {
        if (n % 2) {
            ret *= x;
            ret %= MOD;
        }
        x *= x;
        x %= MOD;
        n /= 2;
    }
    return ret;
}

void get_factors(int n, map<int,int>& m) {
    int i;
    i = 2;
    while (i*i <= n) {
        if (n % i == 0) {
            m[i]++;
            n /= i;
        }
        else
            i++;
    }
    m[n]++;
}

int main() {
    int i, n, k;
    ll ans;
    map<int,vector<int>> factors;
    cin >> n >> k;
    rep (i,n) {
        int a;
        map<int,int> m;
        cin >> a;
        get_factors(a,m);
        for (auto&& p : m)
            factors[p.first].push_back(p.second);
    }
    ans = 1;
    for (auto&& m : factors) {
        int sum = 0;
        sort(m.second.begin(),m.second.end(),greater<int>{});
        rep (i,min(k,(int)m.second.size())) sum += m.second[i];
        ans *= power(m.first,sum);
        ans %= MOD;
    }
    cout << ans << endl;
    return 0;
}