TrickGCD
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 3226 Accepted Submission(s): 1206
Problem Description
You are given an array A , and Zhu wants to know there are how many different array B satisfy the following conditions?
- 1≤Bi≤Ai
- For each pair( l , r ) (1≤l≤r≤n) , gcd(bl,bl+1…br)≥2
Input
The first line is an integer T(1≤T≤10) describe the number of test cases.
Each test case begins with an integer number n describe the size of array A.
Then a line contains n numbers describe each element of A
You can assume that 1≤n,Ai≤105
Output
For the kth test case , first output "Case #k: " , then output an integer as answer in a single line . because the answer may be large , so you are only need to output answer mod 109+7
Sample Input
1
4
4 4 4 4
Sample Output
Case #1: 17
题意:给你一个A数组,求B数组的个数,B数组要满足这几个条件
Bi≤Ai
Gcd(B1,B2,……,Bn)≥2
思路:易发现答案是枚举gcd从2开始到ai中最小的数的数量
那么我们可以从2开始枚举gcd,ai/gcd就是比ai小的数里面有几个数含有gcd为因子的数所以也就是
这个式子
∑
∏
⌊
a
i
g
c
d
⌋
\sum \prod \left \lfloor\frac{a_{i}}{gcd} \right \rfloor
∑∏⌊gcdai⌋但直接算会有重复,这就引进了莫比乌斯函数,利用不同的gcd的值应该互质,也就和莫比乌斯函数一致了
∑
−
μ
(
d
)
∏
⌊
a
i
g
c
d
⌋
\sum -\mu (d)\prod \left \lfloor\frac{a_{i}}{gcd} \right \rfloor
∑−μ(d)∏⌊gcdai⌋
直接一个一个计算的话会超时,那么我们发现3-5除于3的值都是1,而且当其越大这个区间也就越大,我们可以利用前缀和的方法来减少时间
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int mod=1000000007;
using namespace std;
const int maxn=100005;
int prime[maxn];
int mu[maxn];
bool vis[maxn];
int cnt;
int sum[maxn];
void Init(){
int N=maxn;
memset(prime,0,sizeof(prime));
memset(mu,0,sizeof(mu));
memset(vis,0,sizeof(vis));
mu[1] = 1;
cnt = 0;
for(int i=2; i<N; i++){
if(!vis[i]){
prime[cnt++] = i;
mu[i] = -1;
}
for(int j=0; j<cnt&&i*prime[j]<N; j++){
vis[i*prime[j]] = 1;
if(i%prime[j]) mu[i*prime[j]] = -mu[i];
else{
mu[i*prime[j]] = 0;
break;
}
}
}
}
long long quickmod(long long a,long long n)
{
long long ans=1;
a=a%mod;
while(n>0)
{
if(n%2==1)
ans=ans*a%mod;
n/=2;
a=a*a%mod;
}
return ans;
}
int main()
{
Init();
int t,cas=1;
scanf("%d",&t);
while(t--)
{
memset(sum,0,sizeof(sum));
int n;
scanf("%d",&n);
int min1=mod;
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
sum[x]++;
min1=min(min1,x);
}
for(int i=1;i<maxn;i++) sum[i]+=sum[i-1];
long long ans=0;
for(int i=2;i<=min1;i++)
{
long long temp=1;
for(int j=i;j<maxn;j+=i)
temp=temp*quickmod(j/i,sum[min(j+i-1,maxn-1)]-sum[j-1])%mod;
ans=(ans+temp*mu[i]*-1+mod)%mod;
}
printf("Case #%d: ",cas++);
printf("%lld\n",ans);
}
return 0;
}