You are given an array of positive integers $a = [a_0, a_1, \dots, a_{n - 1}]$ ($n \ge 2$).

In one step, the array $a$ is replaced with another array of length $n$, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the $(n - 1)$-th element is the $0$-th element).

Formally speaking, a new array $b = [b_0, b_1, \dots, b_{n - 1}]$ is being built from array $a = [a_0, a_1, \dots, a_{n - 1}]$ such that $b_i$ $= \gcd(a_i, a_{(i + 1) \mod n})$, where $\gcd(x, y)$ is the greatest common divisor of $x$ and $y$, and $x \mod y$ is the remainder of $x$ dividing by $y$. In one step the array $b$ is built and then the array $a$ is replaced with $b$ (that is, the assignment $a$ := $b$ is taking place).

For example, if $a = [16, 24, 10, 5]$ then $b = [\gcd(16, 24)$, $\gcd(24, 10)$, $\gcd(10, 5)$, $\gcd(5, 16)]$ $= [8, 2, 5, 1]$. Thus, after one step the array $a = [16, 24, 10, 5]$ will be equal to $[8, 2, 5, 1]$.

For a given array $a$, find the minimum number of steps after which all values $a_i$ become equal (that is, $a_0 = a_1 = \dots = a_{n - 1}$). If the original array $a$ consists of identical elements then consider the number of steps is equal to $0$.


-----Input-----

The first line contains an integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.

Each test case contains two lines. The first line contains an integer $n$ ($2 \le n \le 2 \cdot 10^5$) — length of the sequence $a$. The second line contains $n$ integers $a_0, a_1, \dots, a_{n - 1}$ ($1 \le a_i \le 10^6$).

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.


-----Output-----

Print $t$ numbers — answers for each test case.


-----Examples-----

Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1


-----Note-----

None

Source: codeforces | Difficulty: HARD
Tags: Sorting

Amortized analysis

Complete search

Number theory

Divide and conquer

Data structures


Solutions:
import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(iinp()):
	n = iinp()
	arr = lmp()
	g = 0
	for i in arr:
		g = gcd(g, i)
	for i in range(n):
		arr[i] //= g
	ans = 0
	for i in range(n):
		g1 = arr[i]
		g2 = arr[(i + 1) % n]
		ind = i
		while g1 != g2:
			g1 = gcd(g1, arr[ind % n])
			g2 = gcd(g2, arr[(ind + 1) % n])
			ind += 1
		ans = max(ans, ind - i - 1)
	print(ans)


from sys import stdin, stdout

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def build(n, sega):
	for i in range(n - 1, -1, -1):
		sega[i] = gcd(sega[i * 2], sega[i * 2 + 1])

def query(n, sega, l, r):
	l += n
	r += n
	res = -1
	while l < r:
		if l & 1 == 1:
			if res == -1:
				res = sega[l]
			else:
				res = gcd(res, sega[l])
			l += 1
		if r & 1 == 1:
			r -= 1
			if res == -1:
				res = sega[r]
			else:
				res = gcd(res, sega[r])
		l //= 2
		r //= 2
	return res
N = 400000
sega = [0] * N
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a_a = list(map(int, stdin.readline().split()))
	for i in range(n):
		sega[n + i] = a_a[i]
	build(n, sega)
	l = 0
	h = n - 1
	while l < h:
		m = (l + h) // 2
		flag = True
		r = query(n, sega, 0, m + 1)
		for i in range(1, n):
			tmp = query(n, sega, i, min(n, i + m + 1))
			if i + m + 1 > n:
				tmp = gcd(tmp, query(n, sega, 0, i + m + 1 - n))
			if r != tmp:
				flag = False
				break
		if flag:
			h = m
		else:
			l = m + 1
	stdout.write(str(h) + '\n')


import sys
sys.stderr = sys.stdout
from math import gcd

def primes(m):
	S = [True] * (m + 1)
	S[0] = S[1] = False
	P = []
	for i in range(2, m + 1):
		if S[i]:
			P.append(i)
			for j in range(i * i, m + 1, i):
				S[j] = False
	return P
P = {p: None for p in primes(10 ** 6)}

def pf(k):
	if k == 1:
		return set()
	if k in P:
		return {k}
	S = set()
	for p in P:
		(q, r) = divmod(k, p)
		if r == 0:
			S.add(p)
			while r == 0:
				k = q
				(q, r) = divmod(k, p)
			if k == 1:
				return S
			if k in P:
				S.add(k)
				return S

def solve(n, A):
	g = 0
	for a in A:
		g = gcd(g, a)
	B = [pf(a // g) for a in A]
	m = 0
	for i in range(n):
		for p in B[i] - B[i - 1]:
			j = i + 1 - n
			while p in B[j]:
				B[j].remove(p)
				j += 1
			m = max(m, (j - i) % n)
	return m

def case():
	n = readint()
	A = readintl()
	return str(solve(n, A))

def main():
	t = readint()
	print('\n'.join((case() for _ in range(t))))

def readint():
	return int(input())

def readinti():
	return map(int, input().split())

def readintt():
	return tuple(readinti())

def readintl():
	return list(readinti())

def readinttl(k):
	return [readintt() for _ in range(k)]

def readintll(k):
	return [readintl() for _ in range(k)]

def lstr(l):
	return ' '.join(map(str, l))

def llstr(ll):
	return '\n'.join(map(lstr, ll))

def log(*args, **kwargs):
	print(*args, **kwargs, file=sys.__stderr__)
main()


import sys
import math
mod = 10 ** 9 + 7
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
for t in r(IN()):
	n = IN()
	li = LI()
	g = 0
	for i in range(n):
		g = math.gcd(g, li[i])
	for i in range(n):
		li[i] //= g
	ans = 0
	for i in range(n):
		j = i
		num1 = li[i]
		num2 = li[(i + 1) % n]
		while num1 != num2:
			j += 1
			num1 = math.gcd(num1, li[j % n])
			num2 = math.gcd(num2, li[(j + 1) % n])
		ans = max(ans, j - i)
	print(ans)


import math

class SegmentTree:

	def __init__(self, nums) -> None:
		self.l = len(nums)
		self.tree = [0] * self.l + nums
		for i in range(self.l - 1, 0, -1):
			self.tree[i] = math.gcd(self.tree[2 * i], self.tree[2 * i + 1])

	def sumRange(self, i, j):
		m = self.l + i
		n = self.l + j
		res = self.tree[m]
		while m <= n:
			if m & 1:
				res = math.gcd(res, self.tree[m])
				m += 1
			m >>= 1
			if n & 1 == 0:
				res = math.gcd(res, self.tree[n])
				n -= 1
			n >>= 1
		return res

def check(m, n):
	st = set()
	for i in range(n):
		st.add(seg.sumRange(i, i + m - 1))
	if len(st) == 1:
		return 1
for _ in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	seg = SegmentTree(num + num)
	low = 1
	high = n
	ans = n
	while low <= high:
		mid = (low + high) // 2
		if check(mid, n) == 1:
			ans = mid
			high = mid - 1
		else:
			low = mid + 1
	print(ans - 1)


import math
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	(allthesame, gcd) = (1, a[0])
	for j in range(n):
		if a[j] != a[0]:
			allthesame = 0
		gcd = math.gcd(a[j], gcd)
	if allthesame == 1:
		print('0')
		continue
	(ans, seq) = (0, [])
	for j in range(2 * n):
		rj = j % n
		seq2 = []
		for k in range(len(seq)):
			seq[k][0] = math.gcd(seq[k][0], a[rj])
			if seq[k][0] == gcd:
				ans = max(ans, seq[k][1] + 1)
			else:
				seq[k][1] = seq[k][1] + 1
				if k == 0 or seq[k][0] != seq[k - 1][0]:
					seq2.append(seq[k])
		if j < n:
			if len(seq) == 0 or a[j] != seq[len(seq) - 1][0]:
				seq2.append([a[j], 0])
		seq = seq2
	print(ans)


import sys
from functools import reduce
from math import gcd

def main():

	class RangeQuery:

		def __init__(self, data, func=min):
			self.func = func
			self._data = _data = [list(data)]
			(i, n) = (1, len(_data[0]))
			while 2 * i <= n:
				prev = _data[-1]
				_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
				i <<= 1

		def query(self, start, stop):
			depth = (stop - start).bit_length() - 1
			return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

		def __getitem__(self, idx):
			return self._data[0][idx]
	inp = [int(x) for x in sys.stdin.read().split()]
	ii = 0
	t = inp[ii]
	ii += 1
	for _ in range(t):
		n = inp[ii]
		ii += 1
		ar = inp[ii:ii + n]
		ii += n
		ar = ar + ar
		spt = RangeQuery(ar, gcd)
		target = spt.query(0, n)
		ans = 0
		for i in range(n):
			for l in range(ans + 1, n + 1):
				g = spt.query(i, i + l)
				if g == target:
					ans = max(ans, l - 1)
					break
		print(ans)
main()


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
import math

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
t = int(input())
for _ in range(t):

	def buildSparseTable(arr, n):
		for i in range(0, n):
			table[i][0] = arr[i]
		j = 1
		while 1 << j <= n:
			i = 0
			while i <= n - (1 << j):
				table[i][j] = math.gcd(table[i][j - 1], table[i + (1 << j - 1)][j - 1])
				i += 1
			j += 1

	def query(L, R):
		j = int(math.log2(R - L + 1))
		return math.gcd(table[L][j], table[R - (1 << j) + 1][j])
	n = int(input())
	table = [[0 for i in range(20)] for j in range(2 * n)]
	a = list(map(int, input().split()))
	g = a[0]
	i = 1
	while i < n:
		g = gcd(g, a[i])
		i += 1
	res = []
	for j in range(2 * n):
		res.append(a[j % n])
	buildSparseTable(res, 2 * n)
	ans = 0
	for i in range(n):
		l = 0
		r = n - 1
		while l < r:
			m = (l + r) // 2
			g1 = query(i, i + m)
			if g1 == g:
				r = m
			else:
				l = m + 1
		ans = max(ans, l)
	print(ans)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from math import gcd
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

class RangeQuery:

	def __init__(self, data, func=min):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]

def discrete_binary_search(func, lo, hi):
	while lo < hi:
		mi = lo + (hi - lo) // 2
		if func(mi):
			hi = mi
		else:
			lo = mi + 1
	return lo

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = [int(ai) for ai in input().split()]
		rgq = RangeQuery(a * 2, gcd)
		g = rgq.query(0, n)
		sol = 0
		for i in range(n):
			r = discrete_binary_search(lambda x: rgq.query(i, i + x) == g, 1, n) - 1
			sol = max(sol, r)
		print(sol)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys, os, io
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd

class SegmentTree:

	def __init__(self, data, default=0, func=gcd):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	l += l
	seg = SegmentTree(l)
	g = seg.query(0, n)
	low = 1
	high = n
	ans = 1000000000000000000
	while low <= high:
		mid = (low + high) // 2
		f = 0
		for i in range(n):
			cur = seg.query(i, i + mid)
			if cur != g:
				f = 1
				break
		if f == 1:
			low = mid + 1
		else:
			ans = min(mid - 1, ans)
			high = mid - 1
	print(ans)


from math import *
from collections import *
t = int(input())

def getVal(l, sp, d):
	ans = 0
	while d:
		di = int(log2(d))
		ans = gcd(ans, sp[di][l])
		di = 2 ** di
		l += di
		d -= di
	return ans

def isPos(sp, mid, n):
	prev = getVal(0, sp, mid)
	for i in range(1, n):
		if prev != getVal(i, sp, mid):
			return 0
	return 1

def sparsiTable(a, n):
	d = int(log2(n))
	sp = []
	sp.append([])
	for i in range(n + n - 1):
		sp[-1].append(gcd(a[i], a[i + 1]))
	for i in range(1, d + 1):
		di = 2 ** (i - 1)
		lst = []
		for i in range(n + n):
			if i + di < len(sp[-1]):
				lst.append(gcd(sp[-1][i], sp[-1][i + di]))
		sp.append(lst)
	return sp
for _ in range(t):
	n = int(input())
	a = [int(v) for v in input().split()]
	f = Counter(a)
	if f[a[0]] == n:
		print(0)
		continue
	for i in range(n):
		a.append(a[i])
	sp = sparsiTable(a, n)
	(left, right) = (1, n - 1)
	ans = 0
	while left <= right:
		mid = (left + right) // 2
		if isPos(sp, mid, n) == 0:
			left = mid + 1
		else:
			right = mid - 1
			ans = mid
	print(ans)


import math as _math
import sys as _sys

def how_many_steps_array_need_to_become_stable(array):
	array = tuple(array)

	def is_enough_steps(steps_n):
		values_after_this = _make_n_steps(array, steps_n=steps_n)
		array_is_already_stable = len(set(values_after_this)) <= 1
		return array_is_already_stable
	min_steps_n = 0
	max_steps_n = len(array) - 1
	while min_steps_n != max_steps_n:
		steps_n = (min_steps_n + max_steps_n) // 2
		if is_enough_steps(steps_n):
			max_steps_n = steps_n
		else:
			min_steps_n = steps_n + 1
	steps_n_need = min_steps_n
	return steps_n_need

def _make_n_steps(array, *, steps_n):
	array = tuple(array)
	segtree = _ImmutableSegTree(array, function=_math.gcd, neutral_element=0)

	def new_value_by_index(index):
		l = index
		r = index + steps_n
		return segtree.query_on_cyclic(l, r)
	result_array = map(new_value_by_index, range(len(array)))
	result_array = tuple(result_array)
	return result_array

class _ImmutableSegTree:

	def __init__(self, initial_values, *, function, neutral_element):
		self._function = function
		self._neutral_element = neutral_element
		initial_values = tuple(initial_values)
		self._size = len(initial_values)
		initial_values = self._adapt_initial_sequence(initial_values)
		self._raw_begin = len(initial_values)
		sentinel = object()
		self._data = [sentinel] * self._raw_begin + initial_values
		i_parent = self._raw_begin - 1
		while i_parent >= 1:
			self._data[i_parent] = function(self._data[2 * i_parent], self._data[2 * i_parent + 1])
			i_parent -= 1

	def __len__(self):
		return self._size

	def _adapt_initial_sequence(self, sequence):
		sequence = list(sequence)
		final_length = 1
		while final_length < len(sequence):
			final_length *= 2
		while len(sequence) < final_length:
			sequence.append(self._neutral_element)
		return sequence

	def query(self, l, r):
		if not 0 <= l <= r + 1 <= self._size:
			raise IndexError
		result = self._neutral_element
		l += self._raw_begin
		r += self._raw_begin
		while l <= r:
			if l % 2 != 0:
				result = self._function(result, self._data[l])
				l += 1
			if r % 2 == 0:
				result = self._function(result, self._data[r])
				r -= 1
			l //= 2
			r //= 2
		return result

	def query_on_cyclic(self, l, r):
		while l < 0:
			l += self._size
			r += self._size
		while l >= self._size:
			l -= self._size
			r -= self._size
		assert 0 <= l < self._size
		result = self.query(l, min(r, self._size - 1))
		r -= self._size
		del l
		while r >= 0:
			next_part = self.query(0, min(r, self._size - 1))
			result = self._function(result, next_part)
			r -= self._size
		return result

def _main():
	[tests_n] = _read_ints()
	for i_test in range(tests_n):
		[array_length] = _read_ints()
		array = tuple(_read_ints())
		assert len(array) == array_length
		steps_need = how_many_steps_array_need_to_become_stable(array)
		print(steps_need)

def _read_ints():
	return map(int, _sys.stdin.readline().split())
_main()


import os
import sys
from io import BytesIO, IOBase
from math import gcd

def query(l, r, sparse):
	zz = (r - l + 1).bit_length() - 1
	return gcd(sparse[zz][l], sparse[zz][r - (1 << zz) + 1])

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		final = 0
		for i in range(n):
			final = gcd(final, a[i])
		for i in range(n):
			a[i] //= final
		a += a
		n <<= 1
		ans = 0
		size = n.bit_length()
		sparse = [[0 for _ in range(n)] for _ in range(size)]
		sparse[0] = a
		for r in range(1, size):
			for c in range(n - (1 << r) + 1):
				sparse[r][c] = gcd(sparse[r - 1][c], sparse[r - 1][c + (1 << r - 1)])
		for i in range(n >> 1):
			(h, l, z) = (n - 1, i, n - 1)
			while h >= l:
				mid = h + l >> 1
				if query(i, mid, sparse) == 1:
					z = mid
					h = mid - 1
				else:
					l = mid + 1
			ans = max(ans, z - i)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from math import gcd
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = a + a
	m = 0
	for i in range(n):
		k1 = a[i]
		k2 = a[i + 1]
		c = 0
		j = i + 1
		while k1 != k2:
			k1 = gcd(k1, a[j])
			k2 = gcd(k2, a[j + 1])
			j += 1
			c += 1
		m = max(m, c)
	print(m)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def LI1():
	return list(map(int1, sys.stdin.readline().split()))

def LLI1(rows_number):
	return [LI1() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline().rstrip()
inf = 10 ** 16
md = 10 ** 9 + 7

class SparseTableGcd:

	def __init__(self, aa):
		w = len(aa)
		h = w.bit_length()
		table = [aa] + [[0] * w for _ in range(h - 1)]
		tablei1 = table[0]
		for i in range(1, h):
			tablei = table[i]
			for j in range(w - (1 << i) + 1):
				rj = j + (1 << i - 1)
				tablei[j] = gcd(tablei1[j], tablei1[rj])
			tablei1 = tablei
		self.table = table

	def prod(self, l, r):
		i = (r - l).bit_length() - 1
		tablei = self.table[i]
		Lmax = tablei[l]
		Rmax = tablei[r - (1 << i)]
		return gcd(Lmax, Rmax)
from math import gcd

def solve():
	n = II()
	aa = LI()
	g = 0
	for a in aa:
		g = gcd(g, a)
	for i in range(n):
		aa[i] //= g
	if sum(aa) == n:
		print(0)
		return
	sp = SparseTableGcd(aa + aa)
	mx = 1
	r = 1
	for l in range(n):
		if r <= l:
			r = l + 1
		while sp.prod(l, r) > 1:
			r += 1
		mx = max(mx, r - l - 1)
	print(mx)
for testcase in range(II()):
	solve()


from math import gcd
import sys
input = sys.stdin.readline

class segtree:

	def __init__(self, Size, e, A=[]):
		self.Size = Size
		for i in range(Size):
			if Size <= 1 << i:
				self.LeavesSize = 1 << i
				break
		self.e = e
		self.Tree = [e] * (self.LeavesSize * 2)
		for i in range(len(A)):
			self.Tree[i + self.LeavesSize - 1] = A[i]
		self.make()

	def make(self, i=0):
		if i < self.LeavesSize - 1:
			self.Tree[i] = gcd(self.make(i * 2 + 1), self.make(i * 2 + 2))
		return self.Tree[i]

	def get2(self, A, B, Index=0, L=0, R=-1):
		if Index == 0:
			R = self.LeavesSize
		if B <= L or R <= A:
			return self.e
		if A <= L and R <= B:
			return self.Tree[Index]
		return gcd(self.get2(A, B, Index * 2 + 1, L, (L + R) // 2), self.get2(A, B, Index * 2 + 2, (L + R) // 2, R))

	def get(self, A, B):
		if B <= self.Size:
			return self.get2(A, B)
		return gcd(self.get2(A, self.Size), self.get2(0, B - self.Size))

def main():
	N = int(input())
	A = list(map(int, input().split()))
	Tree = segtree(N, 0, A)
	P = Tree.get(0, N)
	Ans = 0
	j = 1
	for i in range(N):
		if i == j:
			j += 1
		while Tree.get(i, j) != P:
			j += 1
		if Ans < j - i:
			Ans = j - i
	print(Ans - 1)
T = int(input())
for _ in range(T):
	main()


from math import gcd
from bisect import *
from heapq import *
import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))

def solve(N, nums):
	ans = 0
	valid = True
	while valid:
		valid = False
		next_nums = []
		for i in range(N):
			val = gcd(nums[i], nums[(i + 1) % N])
			if val != nums[i]:
				valid = True
			next_nums.append(val)
		if valid:
			nums = next_nums
			ans += 1
	return ans

def solve2(N, nums):
	q = set()
	for i in range(N):
		j = (i + 1) % N
		if nums[j] >= nums[i] and nums[j] % nums[i] == 0:
			continue
		q.add(i)
	ans = 0
	while q:
		next_q = set()
		next_nums = {}
		for i in q:
			j = (i + 1) % N
			k = (i - 1 + N) % N
			val = gcd(nums[i], nums[j])
			next_nums[i] = val
		for i in q:
			nums[i] = next_nums[i]
		for i in q:
			j = (i + 1) % N
			k = (i - 1 + N) % N
			if nums[j] < nums[i] or (nums[j] > nums[i] and nums[j] % nums[i] != 0):
				next_q.add(i)
			if nums[i] < nums[k] or (nums[i] > nums[k] and nums[i] % nums[k] != 0):
				next_q.add(k)
		q = next_q
		ans += 1
	return ans
T = int(input())
for _ in range(T):
	N = int(input())
	nums = get_ints()
	print(solve2(N, nums))


from collections import defaultdict, Counter
from math import sqrt, log10, log2, log, gcd, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations
import sys, io, os
input = sys.stdin.readline
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = float('inf')
mod = 10 ** 9 + 7

def get_list():
	return [int(i) for i in input().split()]
yn = lambda a: print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b

class LazySegmentTree:

	def __init__(self, data, default=0, func=max):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self._lazy = [0] * (2 * _size)
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __len__(self):
		return self._len

	def _push(self, idx):
		(q, self._lazy[idx]) = (self._lazy[idx], 0)
		self._lazy[2 * idx] += q
		self._lazy[2 * idx + 1] += q
		self.data[2 * idx] += q
		self.data[2 * idx + 1] += q

	def _update(self, idx):
		for i in reversed(range(1, idx.bit_length())):
			self._push(idx >> i)

	def _build(self, idx):
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
			idx >>= 1

	def add(self, start, stop, value):
		start = start_copy = start + self._size
		stop = stop_copy = stop + self._size
		while start < stop:
			if start & 1:
				self._lazy[start] += value
				self.data[start] += value
				start += 1
			if stop & 1:
				stop -= 1
				self._lazy[stop] += value
				self.data[stop] += value
			start >>= 1
			stop >>= 1
		self._build(start_copy)
		self._build(stop_copy - 1)

	def query(self, start, stop, default=0):
		start += self._size
		stop += self._size
		self._update(start)
		self._update(stop - 1)
		res = default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'LazySegmentTree({0})'.format(self.data)
t = int(input())
for i in range(t):
	n = int(input())
	l = get_list()
	gcda = l[0]
	for i in l:
		gcda = gcd(i, gcda)
	l += l
	s = LazySegmentTree(l, 0, gcd)
	maxa = 0
	for i in range(n):
		answer = 0
		low = i
		high = i + n
		while low < high:
			mid = (low + high) // 2
			if s.query(i, mid + 1) == gcda:
				high = mid
				answer = mid - i
			else:
				low = mid + 1
		maxa = max(answer, maxa)
	print(maxa)


from sys import stdin, stdout
from math import gcd
input = stdin.readline

def main():
	t = int(input())
	for z in range(t):
		n = int(input())
		ai = list(map(int, input().split()))
		if n == 1 or max(ai) == min(ai):
			print(0)
			continue
		ans = 1
		ar = [[ai[0], 1]]
		for i in range(1, n):
			ar2 = []
			for num in ar:
				temp = gcd(num[0], ai[i])
				if temp != 1:
					ar2 += [[temp, num[1] + 1]]
				elif temp != num[0]:
					if num[1] < n:
						ans = max(ans, num[1])
			ar2 += [[ai[i], 1]]
			ar2.sort(key=lambda x: x[0])
			ar = [ar2[0]]
			for i in range(1, len(ar2)):
				if ar[-1][0] == ar2[i][0]:
					ar[-1][1] = max(ar[-1][1], ar2[i][1])
				else:
					ar += [ar2[i]]
		for i in range(n):
			ar2 = []
			for num in ar:
				temp = gcd(num[0], ai[i])
				if temp != 1:
					ar2 += [[temp, num[1] + 1]]
				if temp != num[0]:
					if num[1] < n:
						ans = max(ans, num[1])
			ar2 += [[ai[i], 1]]
			ar2.sort(key=lambda x: x[0])
			ar = [ar2[0]]
			for i in range(1, len(ar2)):
				if ar[-1][0] == ar2[i][0]:
					ar[-1][1] = max(ar[-1][1], ar2[i][1])
				else:
					ar += [ar2[i]]
		for num in ar:
			if num[1] < n:
				ans = max(ans, num[1])
		print(ans)
main()


import sys
input = sys.stdin.buffer.readline
import math

def segfunc(x, y):
	return math.gcd(x, y)

class SegmentTree(object):

	def __init__(self, A, dot, unit):
		n = 1 << (len(A) - 1).bit_length()
		tree = [unit] * (2 * n)
		for (i, v) in enumerate(A):
			tree[i + n] = v
		for i in range(n - 1, 0, -1):
			tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
		self._n = n
		self._tree = tree
		self._dot = dot
		self._unit = unit

	def __getitem__(self, i):
		return self._tree[i + self._n]

	def update(self, i, v):
		i += self._n
		self._tree[i] = v
		while i != 1:
			i >>= 1
			self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])

	def add(self, i, v):
		self.update(i, self[i] + v)

	def sum(self, l, r):
		l += self._n
		r += self._n
		l_val = r_val = self._unit
		while l < r:
			if l & 1:
				l_val = self._dot(l_val, self._tree[l])
				l += 1
			if r & 1:
				r -= 1
				r_val = self._dot(self._tree[r], r_val)
			l >>= 1
			r >>= 1
		return self._dot(l_val, r_val)

def main():
	t = int(input())
	INF = pow(10, 18)
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		AS = set(A)
		if len(AS) == 1:
			print(0)
			continue
		z = A[0]
		for i in range(1, n):
			z = math.gcd(z, A[i])
		A = A + A
		Tree = SegmentTree(A, segfunc, 0)

		def check(p, z=z):
			for i in range(n):
				if Tree.sum(i, i + p) == z:
					continue
				return False
			return True
		ok = n
		ng = 0
		while abs(ok - ng) > 1:
			mid = (ok + ng) // 2
			if check(mid):
				ok = mid
			else:
				ng = mid
		print(ok - 1)
main()


import math

class RMQ:

	def __init__(self, arr, min_max):
		self.cache = [arr]
		self.func = min_max
		self.precompute(arr, self.func)

	def precompute(self, arr, min_max):
		max_log = int(math.log2(len(arr)))
		for i in range(1, max_log + 1):
			new_row = []
			for j in range(0, len(arr) - 2 ** i + 1):
				new_row.append(min_max(self.cache[i - 1][j], self.cache[i - 1][j + 2 ** (i - 1)]))
			self.cache.append(new_row)

	def query(self, l, r):
		if l == r:
			return self.cache[0][l]
		if l > r:
			return self.func(self.query(l, n), self.query(0, r))
		log_val = int(math.log2(r - l))
		return self.func(self.cache[log_val][l], self.cache[log_val][r - 2 ** log_val])

def binary_search_leftmost(rmq, min_all, n, cur):
	left = 0
	right = n - 1
	while left < right:
		middle = (left + right) // 2
		if check_smaller(rmq, middle, min_all, cur):
			left = middle + 1
		else:
			right = middle
	return left

def check_smaller(rmq, middle, min_all, cur):
	if (cur + middle) % n + 1 == cur:
		res1 = min_all
	else:
		res1 = rmq.query(cur, (cur + middle) % n + 1)
	if res1 == min_all:
		return False
	return True

def solve(n, seq):
	rmq = RMQ(seq, math.gcd)
	min_all = rmq.query(0, n)
	max_op = 0
	cur = 0
	while cur < n:
		if seq[cur] == min_all:
			cur += 1
			continue
		mid = binary_search_leftmost(rmq, min_all, n, cur)
		if mid > max_op:
			max_op = mid
		cur = cur + 1
	return max_op
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
	n = int(input().decode().strip())
	seq = [int(x) for x in input().decode().strip().split(' ')]
	res = solve(n, seq)
	print(res)


def read_ints():
	return list(map(int, input().split()))

def gcd(x, y):
	if x == 0 or y == 0:
		return x + y
	if x > y:
		return gcd(x % y, y)
	else:
		return gcd(x, y % x)

def remove_gcd(a):
	g = gcd(a[0], a[1])
	for i in range(2, len(a)):
		g = gcd(g, a[i])
	return [x // g for x in a]

def make_cycled(a):
	a.extend(a[:-1])
	return a

def create_dp(a):
	n = len(a)
	k = 0
	while n > 0:
		k += 1
		n //= 2
	dp = [[0 for _ in range(len(a))] for _ in range(k)]
	dp[0] = a
	step = 1
	for i in range(1, k):
		step *= 2
		for j in range(len(a)):
			if j + step <= len(a):
				dp[i][j] = gcd(dp[i - 1][j], dp[i - 1][j + step // 2])
	return dp

def get_seq_gcd(dp, l, r):
	step = 1
	k = -1
	while r - l >= step:
		step *= 2
		k += 1
	step //= 2
	return gcd(dp[k][l], dp[k][r - step])

def get_answer(dp):
	answer = 0
	(l, r) = (0, 1)
	while l < len(dp[0]):
		cur = get_seq_gcd(dp, l, r)
		while r < len(dp[0]) and cur > 1:
			cur = gcd(cur, dp[0][r])
			r += 1
		answer = max(answer, r - l - 1)
		l += 1
		if l == r:
			r += 1
	return answer
t = int(input())
for _ in range(t):
	n = int(input())
	a = read_ints()
	a = remove_gcd(a)
	a = make_cycled(a)
	dp = create_dp(a)
	answer = get_answer(dp)
	print(answer)


from __future__ import print_function
from collections import *
from sys import stdin
import sys
from heapq import *
from math import log2, ceil, sqrt, gcd, log
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()

def table(a, n):
	d = int(log2(n))
	sp = [[gcd(a[i], a[i + 1]) for i in range(n + n - 1)]]
	for i in range(1, d + 1):
		di = 1 << i - 1
		sp.append([])
		for i in range(n + n):
			if i + di < len(sp[-2]):
				sp[-1].append(gcd(sp[-2][i], sp[-2][i + di]))
	return sp

def getVal(l, sp, d):
	gc = 0
	while d:
		di = int(log2(d))
		gc = gcd(gc, sp[di][l])
		di = 1 << di
		d -= di
		l += di
	return gc

def isPos(sp, mid, n):
	prev = getVal(0, sp, mid)
	for i in range(1, n):
		if prev != getVal(i, sp, mid):
			return False
	return True
for _ in range(t):
	(n,) = gil()
	a = gil()
	if a.count(a[0]) == n:
		print(0)
		continue
	a += a
	sp = table(a, n)
	(l, r, ans) = (1, n - 1, 0)
	while l <= r:
		mid = (l + r) // 2
		if isPos(sp, mid, n):
			r = mid - 1
			ans = mid
		else:
			l = mid + 1
	print(ans)


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd

class RangeQuery:

	def __init__(self, data, func=gcd):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	a += a[:]
	g = a[0]
	for i in a:
		g = gcd(i, g)
	rmq = RangeQuery(a)
	l = 1
	h = n
	ans = -1
	while l <= h:
		mid = (l + h) // 2
		flag = 0
		for i in range(n):
			curr = rmq.query(i, i + mid)
			if curr != g:
				flag = 1
		if flag:
			l = mid + 1
		else:
			ans = mid - 1
			h = mid - 1
	print(ans)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound

def so():
	return int(input())

def st():
	return input()

def mj():
	return map(int, input().strip().split(' '))

def msj():
	return map(str, input().strip().split(' '))

def le():
	return list(map(int, input().split()))

def lebe():
	return list(map(int, input()))

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()

def joro(L):
	return ''.join(map(str, L))

def cheems(c, d):
	a = 1
	while d != 0:
		if d % 2 == 1:
			a *= c
		c = c * c
		d = d // 2
	return a

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def npr(n, r):
	return factorial(n) // factorial(n - r) if n >= r else 0

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def tir(a, b, c):
	if 0 == c:
		return 1
	if len(a) <= b:
		return 0
	if c != -1:
		return tir(a, 1 + b, c + a[b]) or tir(a, b + 1, c - a[b]) or tir(a, 1 + b, c)
	else:
		return tir(a, 1 + b, a[b]) or tir(a, b + 1, -a[b]) or tir(a, 1 + b, -1)

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = -1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def wubu(m):
	import math as my
	d = 0
	while not m % 2:
		m = m // 2
		d = 1 + d
	for i in range(3, int(my.sqrt(m)) + 1, 2):
		while not m % i:
			m = m // i
			d = 1 + d
	return int(m > 1) + d

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	li = []
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, len(prime)):
		if prime[p]:
			li.append(p)
	return li

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def tr(n):
	return n * (n + 1) // 2

def bro(q, r, c):
	(bec, pot, h) = (0, 0, 0)
	ds = []
	bs = []
	es = []
	for i in range(c):
		while h < len(r) and r[h] <= q[i][0]:
			pot = 0
			ds.clear()
			bs.clear()
			h = 1 + h
	for i in range(c):
		ds.append(q[i][1])
		es.append(q[i][1])
	ds = list(set(ds))
	for i in ds:
		bs.append(es.count(i))
	print(bs)
	for i in range(c):
		if q[i][0] > r[h - 1]:
			bec = bec + pot - bs[i]
			pot = 1 + pot
	return bec

def iu():
	import sys
	input = sys.stdin.readline
	import math as my
	import bisect as op
	c = 0
	m = so()
	L = le()
	L = 2 * L
	for i in range(m):
		(p, q, r, s) = (L[i], L[1 + i], 0, 1 + i)
		while q != p:
			(p, q, r, s) = (my.gcd(L[s], p), my.gcd(L[1 + s], q), 1 + r, 1 + s)
		c = max(r, c)
	print(c)

def main():
	for i in range(so()):
		iu()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations, combinations_with_replacement, product
from collections import *
M = 10 ** 9 + 7
import heapq
from bisect import *
from functools import lru_cache
from queue import PriorityQueue
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def query1(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

def rse(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(n)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(n)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def lse(arr, n):
	stack = []
	ans = []
	for i in range(n):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	return ans

def mah(arr):
	max1 = 0
	p = rse(arr, len(arr))
	q = lse(arr, len(arr))
	for i in range(len(arr)):
		a = (p[i] - q[i] - 1) * arr[i]
		max1 = max(a, max1)
	return max1

def maxSumIS(arr, n):
	msis = arr.copy()
	for i in range(1, n):
		for j in range(i):
			if arr[i] > arr[j] and msis[i] < msis[j] + arr[i]:
				msis[i] = msis[j] + arr[i]
	c = max(msis)
	p = 5
	return c

def binarysearch2(arr, target):
	lo = 0
	hi = len(arr) - 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if arr[mid] == target:
			if mid != len(arr) - 1:
				if arr[mid + 1] != target:
					return mid
				else:
					lo += 1
			else:
				return mid
			continue
		if arr[mid] > target:
			hi = mid - 1
		else:
			lo = mid + 1

def ngr(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) > 0:
				if stack[-1][0] < arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def alperm(nums, path, result):
	if not nums:
		result.add(tuple(path))
		return
	for i in range(0, len(nums)):
		alperm(nums[:i] + nums[i + 1:], path + [nums[i]], result)
	return result

def minsum(arr, n, m, res, l):
	if n == 1 and m == 1:
		res += arr[0][0]
		l.append(res)
	else:
		if n != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n - 1, m, p, l)
		if m != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n, m - 1, p, l)
	return min(l)

def subset(arr, n, ans, c):
	if n == 0:
		print(c)
		ans.add(tuple(sorted(c)))
		return
	else:
		op = c + [arr[n - 1]]
		subset(arr, n - 1, ans, op)
		subset(arr, n - 1, ans, c)

def catalan(n):
	if n == 0 or n == 1:
		return 1
	catalan = [0] * (n + 1)
	catalan[0] = 1
	catalan[1] = 1
	for i in range(2, n + 1):
		for j in range(i):
			catalan[i] += catalan[j] * catalan[i - j - 1]
	return catalan[n]

def isP(p, i, j):
	if j <= i:
		return True
	if p[i] != p[j]:
		return False
	return isP(p, i + 1, j - 1)

def main():
	t = 1
	t = inpu()
	for _ in range(t):
		n = inpu()
		arr = lis()
		res = 0
		if len(set(arr)) == 1:
			print(0)
			continue
		arr += arr
		m = 0
		for i in range(n):
			k1 = arr[i]
			k2 = arr[i + 1]
			c = 0
			j = i + 1
			while k1 != k2:
				k1 = math.gcd(k1, arr[j])
				k2 = math.gcd(k2, arr[j + 1])
				j += 1
				c += 1
			m = max(m, c)
		print(m)
main()


import sys
from sys import stdin
import math

class SegTree:

	def __init__(self, N, first):
		self.NO = 2 ** (N - 1).bit_length()
		self.First = first
		self.data = [first] * (2 * self.NO)

	def calc(self, l, r):
		if l == -1 or r == -1:
			return max(l, r)
		return math.gcd(l, r)

	def update(self, ind, x):
		ind += self.NO - 1
		self.data[ind] = x
		while ind >= 0:
			ind = (ind - 1) // 2
			self.data[ind] = self.calc(self.data[2 * ind + 1], self.data[2 * ind + 2])

	def query(self, l, r):
		L = l + self.NO
		R = r + self.NO
		s = self.First
		while L < R:
			if R & 1:
				R -= 1
				s = self.calc(s, self.data[R - 1])
			if L & 1:
				s = self.calc(s, self.data[L - 1])
				L += 1
			L >>= 1
			R >>= 1
		return s

	def get(self, ind):
		ind += self.NO - 1
		return self.data[ind]
tt = int(stdin.readline())
ANS = []
for loop in range(tt):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	a.reverse()
	ST = SegTree(2 * n, -1)
	for i in range(n):
		ST.update(i, a[i])
		ST.update(i + n, a[i])
	allg = ST.query(0, 2 * n)
	ans = 0
	for l in range(n):
		r = l + ans
		if r >= 2 * n:
			break
		g = ST.query(l, r + 1)
		if g == allg:
			continue
		while r + 1 < 2 * n:
			r += 1
			g = math.gcd(g, a[r % n])
			if g == allg:
				ans = max(ans, r - l)
				break
	ANS.append(str(ans))
print('\n'.join(ANS))


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd

class SegmentTree:

	def __init__(self, data, default=1, func=gcd):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = -1
		while start < stop:
			if start & 1:
				if res_left == -1:
					res_left = self.data[start]
				else:
					res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				if res_right == -1:
					res_right = self.data[stop]
				else:
					res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		if res_left == -1:
			return res_right
		elif res_right == -1:
			return res_left
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	a += a[:]
	g = a[0]
	for i in a:
		g = gcd(i, g)
	st = SegmentTree(a)
	l = 0
	h = n
	ans = -1
	while l <= h:
		mid = (l + h) // 2
		flag = 0
		for i in range(n):
			curr = st.query(i, i + mid)
			if curr != g:
				flag = 1
		if flag:
			l = mid + 1
		else:
			ans = mid - 1
			h = mid - 1
	print(ans)


from math import gcd

def solve():
	ans = 0
	for i in range(n):
		x = a[i]
		y = a[i + 1]
		c = 0
		j = i + 1
		while x != y:
			x = gcd(x, a[j])
			y = gcd(y, a[j + 1])
			j += 1
			c += 1
		ans = max(ans, c)
	return ans
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a += a
	print(solve())


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

def li():
	return list(map(int, sys.stdin.readline().split()))

def mp():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(sys.stdin.readline())

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():

	def query(a, b):
		a += N
		b += N
		c = 0
		while a <= b:
			if a % 2:
				c = gcd(c, seg[a])
				a += 1
			if b % 2 == 0:
				c = gcd(c, seg[b])
				b -= 1
			b >>= 1
			a >>= 1
		return c
	n = inp()
	l = li()
	l += l
	N = 2 * n
	seg = [0] * N + list(l)
	for i in range(N - 1, -1, -1):
		seg[i] = gcd(seg[2 * i], seg[2 * i + 1])
	low = 0
	high = N
	ans = -1
	while low <= high:
		mid = (low + high) // 2
		cur = []
		for i in range(n):
			cur.append(query(i, i + mid))
		if min(cur) == max(cur):
			ans = mid
			high = mid - 1
		else:
			low = mid + 1
	pr(ans)
for _ in range(inp()):
	solve()


from math import gcd
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a += a
	end_val = 0
	for i in a:
		end_val = gcd(end_val, i)
	g = [[0] * 30 for i in range(len(a))]
	for i in range(len(a)):
		g[i][0] = a[i]
	for j in range(1, 30):
		for i in range(len(a)):
			if i + (1 << j) <= 2 * n:
				g[i][j] = gcd(g[i][j - 1], g[i + (1 << j - 1)][j - 1])
	min_steps = [0] * n
	curr_gcd = [0] * n
	for i in range(n):
		for j in range(29, -1, -1):
			if min_steps[i] + (1 << j) <= n:
				new_gcd = gcd(g[i + min_steps[i]][j], curr_gcd[i])
				if new_gcd > end_val:
					min_steps[i] += 1 << j
					curr_gcd[i] = new_gcd
	print(max(min_steps))


import sys
from math import gcd
t = int(sys.stdin.readline())
while t > 0:
	n = int(input())
	a = list(map(int, sys.stdin.readline().split()))
	a = a + a
	m = 0
	for i in range(n):
		x = a[i]
		y = a[i + 1]
		c = 0
		j = i + 1
		while x != y:
			x = gcd(x, a[j])
			y = gcd(y, a[j + 1])
			j += 1
			c += 1
		m = max(m, c)
	print(m)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
from math import inf, log2

class SegmentTree:

	def __init__(self, array, func=max):
		self.n = len(array)
		self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1
		self.func = func
		self.default = 0 if self.func != min else inf
		self.data = [self.default] * (2 * self.size)
		self.process(array)

	def process(self, array):
		self.data[self.size:self.size + self.n] = array
		for i in range(self.size - 1, -1, -1):
			self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1])

	def query(self, alpha, omega):
		if alpha == omega:
			return self.data[alpha + self.size]
		res = self.default
		alpha += self.size
		omega += self.size + 1
		while alpha < omega:
			if alpha & 1:
				res = self.func(res, self.data[alpha])
				alpha += 1
			if omega & 1:
				omega -= 1
				res = self.func(res, self.data[omega])
			alpha >>= 1
			omega >>= 1
		return res

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	a += a
	st = SegmentTree(a, func=gcd)
	target = st.query(0, n - 1)
	ans = 0
	if len(set(a)) == 1:
		print(0)
		continue
	for i in range(n):
		(alpha, omega) = (i, i + n - 1)
		while alpha < omega:
			mid = (alpha + omega) // 2
			if st.query(i, mid) == target:
				omega = mid
			else:
				alpha = mid + 1
		ans = max(ans, alpha - i + 1)
	print(ans - 1)


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys

def input():
	return sys.stdin.readline().rstrip()

def getN():
	return int(input())

def getNM():
	return map(int, input().split())

def getList():
	return list(map(int, input().split()))

def getListGraph():
	return list(map(lambda x: int(x) - 1, input().split()))

def getArray(intn):
	return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]

def segfunc(x, y):
	return math.gcd(x, y)
ide_ele = 0

class SegTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
			k >>= 1

	def query(self, l, r):
		res = self.ide_ele
		l += self.num
		r += self.num
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				res = self.segfunc(res, self.tree[r - 1])
			l >>= 1
			r >>= 1
		return res
T = getN()
for _ in range(T):
	N = getN()
	A = getList()
	A += A

	def f(x):
		seg = SegTree(A, segfunc, ide_ele)
		res = [seg.query(i, i + x) for i in range(N)]
		return all([res[i] == res[0] for i in range(N)])
	ok = N + 1
	ng = 0
	while abs(ok - ng) > 1:
		mid = (ok + ng) // 2
		if f(mid):
			ok = mid
		else:
			ng = mid
	print(ok - 1)


import math
import sys
input = sys.stdin.readline

def make_tree(n):
	i = 2
	while True:
		if i >= n * 2:
			tree = [0] * i
			break
		else:
			i *= 2
	return tree

def initialization(a):
	l = len(tree) // 2
	for i in range(l, l + len(a)):
		tree[i] = a[i - l]
	for i in range(l - 1, 0, -1):
		tree[i] = math.gcd(tree[2 * i], tree[2 * i + 1])
	return

def update(i, x):
	i += len(tree) // 2
	tree[i] = x
	i //= 2
	while True:
		if i == 0:
			break
		tree[i] = math.gcd(tree[2 * i], tree[2 * i + 1])
		i //= 2
	return

def get_gcd(s, t):
	s += len(tree) // 2
	t += len(tree) // 2
	ans = tree[s]
	while True:
		if s > t:
			break
		if s % 2 == 0:
			s //= 2
		else:
			ans = math.gcd(ans, tree[s])
			s = (s + 1) // 2
		if t % 2 == 1:
			t //= 2
		else:
			ans = math.gcd(ans, tree[t])
			t = (t - 1) // 2
	return ans

def binary_search(c1, c2):
	m = (c1 + c2 + 1) // 2
	if abs(c1 - c2) <= 1:
		return m
	else:
		if ok(m):
			c2 = m
		else:
			c1 = m
		return binary_search(c1, c2)

def ok(m):
	g = get_gcd(0, m)
	for i in range(1, n):
		if get_gcd(i, m + i) ^ g:
			return False
	return True
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	tree = make_tree(2 * n + 1)
	initialization(a + a)
	ans = binary_search(-1, n)
	print(ans)


T = int(input())
for ti in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	import math
	K = math.ceil(math.log2(N * 2))
	st = [[0 for i in range(K + 1)] for j in range(N * 2)]
	for i in range(N * 2):
		st[i][0] = A[i % N]
	for j in range(1, K + 1):
		for i in range(N * 2 - (1 << j) + 1):
			st[i][j] = math.gcd(st[i][j - 1], st[i + (1 << j - 1)][j - 1])

	def compute(i, m):
		r = i + m
		ans = 0
		for j in range(K, -1, -1):
			if 1 << j <= r - i + 1:
				ans = math.gcd(ans, st[i][j])
				i += 1 << j
		return ans
	l = -1
	r = N - 1
	while r - l > 1:
		m = (l + r) // 2
		ans = compute(0, m)
		ok = True
		for i in range(1, N):
			if compute(i, m) != ans:
				ok = False
				break
		if ok:
			r = m
		else:
			l = m
	print(r)


import sys, os
from math import *
from bisect import *
from heapq import *
from collections import *
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		nn = int(input())
		n = nn * 2
		arr = list(MI())
		arr += arr
		hcf = 0
		lookup = [[] for i in range(n)]
		for i in range(n):
			lookup[i].append(arr[i])
			hcf = gcd(hcf, arr[i])
		j = 1
		while 1 << j <= n:
			i = 0
			while i + (1 << j) - 1 < n:
				lookup[i].append(gcd(lookup[i][j - 1], lookup[i + (1 << j - 1)][j - 1]))
				i += 1
			j += 1

		def query(L, R):
			j = int(log2(R - L + 1))
			return gcd(lookup[L][j], lookup[R - (1 << j) + 1][j])

		def good(k):
			for i in range(nn):
				(l, r) = (i, i + k)
				if hcf != query(l, r - 1):
					return False
			return True
		(a, b) = (0, nn)
		while a + 1 < b:
			m = (a + b) // 2
			if good(m):
				b = m
			else:
				a = m
		print(max(b - 1, 0))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def MI():
	return map(int, input().split())

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: math.gcd(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	gc = 0
	for i in range(n):
		gc = int(math.gcd(l[i], gc))
	l = l + l + []
	ans = 0
	j = 0
	cur = 0
	s = SegmentTree(l)
	for i in range(n):
		j = max(j, i)
		while j < 2 * n:
			if s.query(i, j) > gc:
				j += 1
			else:
				ans = max(ans, j - i)
				break
	print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: math.gcd(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[n - 1]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] >= key:
			res = arr[mid]
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][0] >= key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = a + a
	s = SegmentTree1(a)
	m = 0
	g = s.query(0, n - 1)
	j = 0
	for i in range(n):
		j = max(j, i)
		if j == i:
			c = a[i]
		else:
			c = s.query(i, j)
		while c != g:
			j += 1
			c = math.gcd(c, a[j])
		m = max(m, j - i)
	print(m)


from math import gcd
import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	if len(set(a)) == 1:
		print(0)
		return
	a = a + a
	LOG = 0
	while 1 << LOG + 1 <= 2 * n:
		LOG += 1
	dp = [[-1] * (LOG + 1) for _ in range(2 * n)]
	for i in range(n):
		dp[i][0] = dp[i + n][0] = a[i]
	for k in range(1, LOG + 1):
		for i in range(2 * n):
			if i + (1 << k) - 1 >= 2 * n:
				continue
			dp[i][k] = gcd(dp[i][k - 1], dp[i + (1 << k - 1)][k - 1])

	def query(i, k):
		L = 0
		while 1 << L + 1 <= k:
			L += 1
		X = dp[i][L]
		Y = dp[i + k - (1 << L)][L]
		return gcd(X, Y)

	def possible(k):
		prev = query(0, k + 1)
		for i in range(1, n):
			if query(i, k + 1) != prev:
				return False
		return True
	(lo, hi) = (0, n - 1)
	while lo + 1 < hi:
		mid = (lo + hi) // 2
		if possible(mid):
			hi = mid
		else:
			lo = mid
	print(hi)
	return
for nt in range(int(input())):
	solve()


import collections as _collections
import functools as _functools
import math as _math
import sys as _sys

class ImmutableSegTree:

	def __init__(self, initial_values, *, function, neutral_element):
		self._function = function
		self._neutral_element = neutral_element
		initial_values = tuple(initial_values)
		self._size = len(initial_values)
		initial_values = self._adapt_initial_sequence(initial_values)
		self._raw_begin = len(initial_values)
		sentinel = object()
		self._data = [sentinel] * self._raw_begin + initial_values
		i_parent = self._raw_begin - 1
		while i_parent >= 1:
			self._data[i_parent] = function(self._data[2 * i_parent], self._data[2 * i_parent + 1])
			i_parent -= 1

	@property
	def size(self):
		return self._size

	def _adapt_initial_sequence(self, sequence):
		sequence = list(sequence)
		final_length = 1
		while final_length < len(sequence):
			final_length *= 2
		while len(sequence) < final_length:
			sequence.append(self._neutral_element)
		return sequence

	def query(self, l, r):
		result = self._neutral_element
		l += self._raw_begin
		r += self._raw_begin
		while l <= r:
			if l % 2 != 0:
				result = self._function(result, self._data[l])
				l += 1
			if r % 2 == 0:
				result = self._function(result, self._data[r])
				r -= 1
			l //= 2
			r //= 2
		return result

def _read_ints():
	return map(int, _sys.stdin.readline().split())

def _make_n_steps(*, array=None, segtree=None, steps_n):
	if segtree is None:
		assert array is not None
		segtree = ImmutableSegTree(array, function=_math.gcd, neutral_element=0)
		array = None
	assert array is None
	del array
	result_array = []
	for l in range(segtree.size):
		r = l + steps_n
		result = segtree.query(l, min(r, segtree.size - 1))
		if r >= segtree.size:
			r -= segtree.size
			second_part = segtree.query(0, min(r, segtree.size - 1))
			result = _math.gcd(result, second_part)
		result_array.append(result)
	return result_array

def how_many_steps_array_need_to_become_stable(array):
	array = tuple(array)
	segtree = ImmutableSegTree(array, function=_math.gcd, neutral_element=0)
	min_steps_n = 0
	max_steps_n = segtree.size - 1
	while min_steps_n != max_steps_n:
		steps_n = (min_steps_n + max_steps_n) // 2
		values_after_this = _make_n_steps(segtree=segtree, steps_n=steps_n)
		array_is_already_stable = len(set(values_after_this)) <= 1
		if array_is_already_stable:
			max_steps_n = steps_n
		else:
			min_steps_n = steps_n + 1
	steps_n_need = min_steps_n
	return steps_n_need

def _main():
	[tests_n] = _read_ints()
	for i_test in range(tests_n):
		[array_length] = _read_ints()
		array = tuple(_read_ints())
		assert len(array) == array_length
		steps_need = how_many_steps_array_need_to_become_stable(array)
		print(steps_need)
_main()


import sys
import math
input = sys.stdin.readline

def sieve(n):
	prime = [-1] * (n + 1)
	for i in range(2, n + 1):
		if prime[i] == -1:
			for j in range(i, n + 1, i):
				if prime[j] == -1:
					prime[j] = i
	return prime

def PrimeFactors(num):
	ans = {}
	while num != 1:
		p = prime[num]
		ans[p] = 1
		while num % p == 0:
			num = num // p
	return ans

def solve(ind, p):
	ans = 0
	for i in range(ind, ind + n):
		if p not in pf[i % n]:
			return ans
		else:
			if i not in done:
				done[i] = {p: 0}
			else:
				done[i][p] = 0
			ans += 1
	return ans
prime = sieve(1000010)
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	hcf = a[0]
	for i in a:
		hcf = math.gcd(hcf, i)
	for i in range(n):
		a[i] = a[i] // hcf
	pf = []
	for i in a:
		pf.append(PrimeFactors(i))
	ans = 0
	done = {}
	for i in range(n):
		for j in pf[i]:
			if i not in done:
				done[i] = {}
			if j not in done[i]:
				ans = max(ans, solve(i, j))
	print(ans)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().strip()

def get_strs():
	return get_str().split(' ')

def flat_list(arr):
	return [item for subarr in arr for item in subarr]

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	_ = get_str()
	a = get_ints()
	b = get_ints()
	f = get_ints()
	z = 0
	if a[0] == b[0] == f[0] and (f[1] - a[1]) * (f[1] - b[1]) < 0:
		z = 2
	elif a[1] == b[1] == f[1] and (f[0] - a[0]) * (f[0] - b[0]) < 0:
		z = 2
	return abs(a[0] - b[0]) + abs(a[1] - b[1]) + z

def solve_b():
	s = get_str()
	n = len(s)
	a = list(string.ascii_lowercase)[:n]
	(i, j) = (0, n - 1)
	while a:
		char = a.pop()
		if s[i] == char:
			i += 1
		elif s[j] == char:
			j -= 1
		else:
			return False
	return True

def solve_c():
	_ = get_str()
	(k, n, m) = get_ints()
	a = get_ints()
	b = get_ints()
	(i, j) = (0, 0)
	r = []
	for _ in range(n + m):
		if i < n and a[i] <= k:
			r.append(a[i])
			if not a[i]:
				k += 1
			i += 1
		elif j < m and b[j] <= k:
			r.append(b[j])
			if not b[j]:
				k += 1
			j += 1
		else:
			return [-1]
	return r

def solve_d():
	n = get_int()
	x = get_ints()
	ans = [0]
	for i in range(1, n):
		tmp = ans[i - 1] ^ x[i - 1]
		new = tmp & ~x[i]
		ans.append(new)
	return ans

def solve_e():
	get_str()
	(n, k) = get_ints()
	a = get_ints()
	x = get_ints()
	coolers = defaultdict(int)
	for i in range(k):
		coolers[a[i] - 1] = x[i]
	p = float('inf')
	tmps = [float('inf')] * n
	for i in range(n):
		p += 1
		if coolers[i]:
			p = min(p, coolers[i])
		tmps[i] = p
	p = float('inf')
	for i in range(n - 1, -1, -1):
		p += 1
		if coolers[i]:
			p = min(p, coolers[i])
		tmps[i] = min(p, tmps[i])
	print(*tmps)

class SparseTableIdempotent:

	def __init__(self, arr, func=min, singleton=float('inf')):
		self.n = len(arr)
		self.log = [-float('inf'), 0]
		for i in range(2, self.n + 1):
			self.log.append(self.log[i // 2] + 1)
		self.m = 1 + self.log[-1]
		self.func = func
		self.sparse_table = [[singleton for _ in range(self.m)] for _ in range(self.n)]
		for i in range(self.n):
			self.sparse_table[i][0] = arr[i]
		for j in range(1, self.m):
			for i in range(self.n - (1 << j) + 1):
				self.sparse_table[i][j] = self.func(self.sparse_table[i][j - 1], self.sparse_table[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		k = self.log[r - l]
		return self.func(self.sparse_table[l][k], self.sparse_table[r - (1 << k)][k])

def solve_f():
	n = get_int()
	a = get_ints()
	ST = SparseTableIdempotent(a, func=math.gcd, singleton=0)

	def good(x):
		S = set()
		for i in range(n):
			if i + x <= n:
				S.add(ST.query(i, i + x))
			else:
				S.add(math.gcd(ST.query(i, n), ST.query(0, x - (n - i))))
			if len(S) > 1:
				return False
		return True
	return binary_search(good, 0, n, right_true=True) - 1
t = get_int()
for _ in range(t):
	print(solve_f())


from math import gcd
import sys
input = sys.stdin.readline

def solve(n, arr):
	if arr.count(arr[0]) == n:
		print(0)
		return
	n *= 2
	tree = [1] * (2 * n)
	for i in range(n):
		tree[n + i] = arr[i % (n // 2)]
	for i in range(n - 1, 0, -1):
		tree[i] = gcd(tree[2 * i], tree[2 * i + 1])

	def get_gcd(a, b, tree):
		res = 0
		a += 2 * n
		b += 2 * n
		while a < b:
			if a & 1:
				res = gcd(tree[a], res)
				a += 1
			if b & 1:
				b -= 1
				res = gcd(tree[b], res)
			a >>= 1
			b >>= 1
		return res
	n //= 2
	answer = get_gcd(0, n, tree)
	count = 1
	a = 0
	b = 2
	while a <= n - 1 and b <= 2 * n - 1:
		if get_gcd(a, b, tree) != answer:
			b += 1
			count += 1
		else:
			a += 1
			b += 1
	print(count)
for _ in range(int(input())):
	solve(int(input()), list(map(int, input().split())))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd

def tree(si, ss, se):
	if ss == se:
		st[si] = l[ss]
		return st[si]
	mid = (ss + se) // 2
	st[si] = gcd(tree(2 * si, ss, mid), tree(2 * si + 1, mid + 1, se))
	return st[si]

def query(si, ss, se, qs, qe):
	if qs > se or qe < ss:
		return 0
	if qs <= ss and qe >= se:
		return st[si]
	mid = (ss + se) // 2
	return gcd(query(2 * si, ss, mid, qs, qe), query(2 * si + 1, mid + 1, se, qs, qe))

def f(a, y, x):
	global g
	i = x
	c = y
	while a != g:
		i += 1
		c += 1
		if i == 2 * n:
			break
		a = gcd(a, l[i])
	return [i, c]
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l += l
	st = [0] * (8 * n + 1)
	tree(1, 0, 2 * n - 1)
	g = 0
	for i in l:
		g = gcd(g, i)
	ans = 0
	i = 0
	j = -1
	while i < n:
		if i > j:
			l1 = f(l[i], 0, i)
			j = l1[0]
			ans = max(ans, l1[1])
		else:
			a = query(1, 0, 2 * n - 1, i, j)
			if a != g:
				l1 = f(gcd(a, l[j + 1]), j - i, j)
				ans = max(ans, l1[1])
				j = l1[0]
		i += 1
	print(ans)


from collections import defaultdict, Counter
from math import sqrt, log10, log2, log, gcd, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations
import sys, io, os
input = sys.stdin.readline
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = float('inf')
mod = 10 ** 9 + 7

def get_list():
	return [int(i) for i in input().split()]
yn = lambda a: print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b

class SegmentTree:

	def __init__(self, data, default=0, func=max):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
t = int(input())
for i in range(t):
	n = int(input())
	l = get_list()
	gcda = l[0]
	for i in l:
		gcda = gcd(i, gcda)
	l += l
	s = SegmentTree(l, 0, gcd)
	maxa = 0
	for i in range(n):
		answer = 0
		low = i
		high = i + n
		while low < high:
			mid = (low + high) // 2
			if s.query(i, mid + 1) == gcda:
				high = mid
				answer = mid - i
			else:
				low = mid + 1
		maxa = max(answer, maxa)
	print(maxa)


import sys
import math
import collections
import heapq
import decimal
input = sys.stdin.readline
t = int(input())
for w in range(t):
	n = int(input())
	l = [int(i) for i in input().split()]
	l = l + l
	m = 0
	for i in range(n):
		k1 = l[i]
		k2 = l[i + 1]
		c = 0
		j = i + 1
		while k1 != k2:
			k1 = math.gcd(k1, l[j])
			k2 = math.gcd(k2, l[j + 1])
			j += 1
			c += 1
		m = max(m, c)
	print(m)


from collections import defaultdict, Counter
from math import sqrt, log10, log2, log, gcd, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations
import sys, io, os
input = sys.stdin.readline
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = float('inf')
mod = 10 ** 9 + 7

def get_list():
	return [int(i) for i in input().split()]
yn = lambda a: print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b

class RangeQuery:

	def __init__(self, data, func=min):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]
t = int(input())
for i in range(t):
	n = int(input())
	l = get_list()
	gcda = l[0]
	for i in l:
		gcda = gcd(i, gcda)
	l += l
	s = RangeQuery(l, gcd)
	maxa = 0
	for i in range(n):
		answer = 0
		low = i
		high = i + n
		while low < high:
			mid = (low + high) // 2
			if s.query(i, mid + 1) == gcda:
				high = mid
				answer = mid - i
			else:
				low = mid + 1
		maxa = max(answer, maxa)
	print(maxa)


def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
ans = []
for _ in range(int(input())):
	n = int(input())
	u = list(map(int, input().split()))
	u += u[:]
	m = 0
	for i in range(n):
		k1 = u[i]
		k2 = u[i + 1]
		c = 0
		j = i + 1
		while k1 != k2:
			k1 = gcd(k1, u[j])
			k2 = gcd(k2, u[j + 1])
			j += 1
			c += 1
		m = max(m, c)
	ans.append(m)
print('\n'.join(map(str, ans)))