# Regarding linear time implementation of shakutori

I introduced this problem before: https://pekempey.hatenablog.com/entry/2018/09/18/085432

This technique can be applied to shakutori (also known as two pointers or sliding window). Its implementation is a little complicated but it might be efficient.

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>

using namespace std;

int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}

int f(vector<int> a) {
const int n = a.size();
int res = 0;
for (int i = 0; i < n; i++) {
int g = 0;
for (int j = i; j < n; j++) {
g = gcd(g, a[j]);
if (g != 1) {
res = max(res, j - i + 1);
}
}
}
return res;
}

int g(vector<int> a) {
const int n = a.size();
vector<pair<int, int>> L, R;
L.emplace_back(0, 0);
R.emplace_back(0, 0);
int j = 0;
int res = 0;
for (int i = 0; i < n; i++) {
while (j < n && gcd(a[j], gcd(L.back().first, R.back().first)) != 1) {
L.emplace_back(gcd(L.back().first, a[j]), a[j]);
j++;
}
res = max(res, j - i);
if (i == j) j++;
else {
if (R.size() == 1) {
while (L.size() >= 2) {
R.emplace_back(gcd(R.back().first, L.back().second), L.back().second);
L.pop_back();
}
}
R.pop_back();
}
}
return res;
}

int main() {
assert(f({1,2,1,2,6,1}) == 2);
assert(f({1,10,1}) == 1);
assert(f({1,1,1}) == 0);
assert(g({1,2,1,2,6,1}) == 2);
assert(g({1,10,1}) == 1);
assert(g({1,1,1}) == 0);
}


This technique is described in [1] : http://hirzels.com/martin/papers/debs17-tutorial.pdf

[1] M. Hirzel, S. Schneider, K. Tangwongsan. Sliding-Window Aggregation Algorithms: Tutorial, DEBS'17 Proceedings of the 11th ACM International Conference on Distributed and Event-based Systems, pp.11--14, 2017.