最大公因数,合并时将两个区间的数跑一次gcd就可以得到gcd啦。
就是max换成gcd。
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 100100;
int n, m, x, y, f[N][30];
int G(int x, int y) {
int r = x % y;
while (r) {
x = y, y = r;
r = x % y;
}
return y;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &f[i][0]);
for (int j = 1; j <= log2(n); j++)
for (int i = 1; i <= n; i++)
if (i + (1 << (j - 1)) > n)//输入后的f数组处理时,遇到超出原数组长度的话,就直接继承上一个
f[i][j] = f[i][j - 1];
else
f[i][j] = G(f[i][j - 1], f[i + (1 << (j - 1))][j - 1]);
for (int i = 1; i <= m; i++) {
scanf("%d %d", &x, &y);
int len = log2(y - x + 1);
printf("%d\n", G(f[x][len], f[y - (1 << len) + 1][len]));
}
return 0;
}