Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
number of (l, r) such that 0<=l <= r <= n-1 and gcd(arr[l], arr[l+1] . . . arr[r]) = 1 using sparse table
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pint pair<int, int>
#define pll pair<ll, ll>
#define mk(a, b) make_pair(a, b)
#define pr(n) printf("%d\n", n)
#define sc(n) scanf ("%d", &n)
#define scll(n) scanf ("%lld", &n)
#define prll(n) printf("%lld\n", n)
#define MOD 1000000007ll
int n, q;
int arr[100000];
int table[100000][16+1]; // 2^16 > 10e5
int k = 16;
void buildTable () {
int i;
for (i = 0; i < n; i++) {
table[i][0] = arr[i];
}
int j;
for (j = 1; j <= k; j++) {
for (i = 0; i <= n-(1<<j); i++) {
table[i][j] = __gcd(table[i][j-1] , table[i+(1<<(j-1))][j-1]);
}
}
return ;
}
int getQuery() {
int i;
int ans = 0;
int temp;
int j;
int g;
for (i = 0; i < n; i++) {
temp = i;
g = 0;
for (j = k; j >= 0; j--) {
if (temp+(1<<j)-1 < n) {
if (__gcd(g, table[temp][j]) > 1) {
temp = temp + (1<<j);
}
}
}
if(temp < n)
ans += (n-temp);
}
return ans;
}
int main (void) {
sc(n);
int i;
for (i = 0; i < n; i++) {
sc(arr[i]);
}
buildTable();
cout<<getQuery()<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.