-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathCount sub-arrays whose product is divisible by k
83 lines (53 loc) · 1.27 KB
/
Count sub-arrays whose product is divisible by k
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<bits/stdc++.h>
using namespace std;
int k;
void build_tree(int*a,int s,int e,int*tree, int index)
{
if(s>e)
return;
if(s==e)
{
tree[index]=a[s]%k;
return;
}
int mid=(s+e)/2;
build_tree(a,s,mid,tree,2*index);
build_tree(a,mid+1,e,tree,2*index+1);
tree[index]=((tree[2*index]%k)*(tree[2*index+1]%k))%k;
return;
}
int query(int*tree,int ts,int te,int qs,int qe,int index)
{
if(ts>qe || te<qs)
return 1;
if(ts>=qs && te<=qe)
return tree[index];
int mid=(ts+te)/2;
int left = query(tree,ts,mid,qs,qe,2*index);
int right= query(tree,mid+1,te,qs,qe,2*index+1);
return ((left%k)*(right%k))%k;
}
int main()
{
int a[]={6,2,8};
k=4;
int n=(sizeof(a)/sizeof(a[0]));
int tree[4*n+1];
build_tree(a,0,n-1,tree,1);
int ans=0;
for(int i=0;i<n;i++)
{
int low=i,high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(query(tree,0,n-1,i,mid,1)==0)
high=mid-1;
else
low=mid+1;
}
ans+=n-low;
}
cout<<ans<<endl;
return 0;
}