牛客 Celestial Resort ###K ###K //K

题目链接:https://ac.nowcoder.com/acm/problem/207703

思路: 很明显求出最小公倍数再除以每个a[i]就是答案, 但是这里求最小公倍数的时候会溢出,所以要配合取模的话就不能用gcd的那种

方法来求了, 因为gcd的过程中有取模,   那么考虑另外一种求lcm的方法, 就是质因数分解的方法, 所有数中,每个质因子最大的指数相乘

如 8 和12  8=2^3 12=2^2*3^1  所以他们的lcm为2^max(2,3)*3^max(0,1)=8*3=24

如果直接暴力求的话 o(n*sqrt(a[i])) 还要套个map在里面会T   用nlogn素数筛 (当然o(n)筛更好)  得出素数

然后 在枚举  这样会在1e8左右, 加上剪枝 一下就能过了  防止T的主要就是 不要让 找质因数的指数的时候的map 遍历太多次, 即x%p[j]!=0的时候continue掉

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 #define ull unsigned long long
 5 #define pb push_back
 6 const int maxn=1e5+10;
 7 const int mod=1e9+7;
 8 ll a[maxn];
 9 ll power(ll base,ll n)
10 {
11     ll r=1;
12     while(n)
13     {
14         if(n&1) r=r*base%mod;
15         base=base*base%mod;
16         n/=2;
17     }
18     return r;
19 }
20 int vis[maxn];
21 int p[maxn];
22 
23 
24 
25 int main()
26 {
27     ios::sync_with_stdio(false);
28     cin.tie(0);
29     int n;
30     cin>>n;
31     map<int,int>mp;
32     for(int i=1;i<=n;i++)
33     {
34         cin>>a[i];
35     }
36     int tot=0;
37     for(int i=2;i<maxn;i++)  //o(nlogn) 筛
38     {
39         if(vis[i])
40             continue;
41         p[tot++]=i;
42         for(int j=i+i;j<maxn;j+=i)
43         {
44             vis[j]=1;
45         }
46     }
47     for(int i=1;i<=n;i++)
48     {
49         ll x=a[i];
50         for(int j=0;j<tot;j++)
51         {
52             if(1ll*p[j]*p[j]>x)   // 这里筛掉能快很多
53                 break;
54             if(x%p[j]==0)
55             {
56                 int cnt=0;
57                 while(x%p[j]==0)
58                 {
59                     x/=p[j];
60                     cnt++;
61                 }
62                 mp[p[j]]=max(mp[p[j]],cnt);
63             }
64         }
65         if(x>1)
66             mp[x]=max(mp[x],1);
67     }
68     ll sum=1;
69     for(auto &v:mp)   //  遍历map o(n)
70     {
71         sum*=power(v.first,v.second);
72         sum%=mod;
73     }
74     ll ans=0;
75     for(int i=1;i<=n;i++)
76     {
77         ans+=sum*power(a[i],mod-2)%mod;
78         ans%=mod;
79     }
80     cout<<ans<<'\n';
81 
82 
83 
84 
85 
86 
87 }
View Code

 

posted @ 2020-07-20 16:40  canwinfor  阅读(161)  评论(0)    收藏  举报