Monocarp has got an array $a$ consisting of $n$ integers. Let's denote $k$ as the mathematic mean of these elements (note that it's possible that $k$ is not an integer).

The mathematic mean of an array of $n$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $n$).

Monocarp wants to delete exactly two elements from $a$ so that the mathematic mean of the remaining $(n - 2)$ elements is still equal to $k$.

Your task is to calculate the number of pairs of positions $[i, j]$ ($i < j$) such that if the elements on these positions are deleted, the mathematic mean of $(n - 2)$ remaining elements is equal to $k$ (that is, it is equal to the mathematic mean of $n$ elements of the original array $a$).


-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.

The first line of each testcase contains one integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of elements in the array.

The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{9}$), where $a_i$ is the $i$-th element of the array.

The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^5$.


-----Output-----

Print one integer — the number of pairs of positions $[i, j]$ ($i < j$) such that if the elements on these positions are deleted, the mathematic mean of $(n - 2)$ remaining elements is equal to $k$ (that is, it is equal to the mathematic mean of $n$ elements of the original array $a$).


-----Examples-----

Input
4
4
8 8 8 8
3
50 20 10
5
1 4 7 3 5
7
1 2 3 4 5 6 7
Output
6
0
2
3


-----Note-----

In the first example, any pair of elements can be removed since all of them are equal.

In the second example, there is no way to delete two elements so the mathematic mean doesn't change.

In the third example, it is possible to delete the elements on positions $1$ and $3$, or the elements on positions $4$ and $5$.

Difficulty: EASY
Tags: Amortized analysis

Implementation

Dynamic programming

Mathematics

Data structures
Skill types: Dynamic programming

Data structures

Amortized analysis

Starter code:

Solutions:
t = int(input())
for _ in range(t):
	n = int(input())
	numbers = list(map(int, input().split()))
	old_sum = sum(numbers)
	if old_sum * (n - 2) % n != 0:
		print(0)
		continue
	new_sum = old_sum * (n - 2) // n
	diff = old_sum - new_sum
	amount = {}
	for x in numbers:
		amount[x] = amount.get(x, 0) + 1
	pairs = 0
	for x in numbers:
		if diff - x in amount:
			pairs += amount[diff - x] - int(diff == 2 * x)
	print(pairs // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	s = sum(arr)
	twoSum = 2 * s / n
	hashmap = {}
	cnt = 0
	for e in arr:
		if twoSum - e in hashmap:
			cnt += hashmap[twoSum - e]
		if e in hashmap:
			hashmap[e] += 1
		else:
			hashmap[e] = 1
	print(cnt)


from sys import stdin
read = stdin.readline
from collections import Counter
for _ in range(int(read())):
	n = int(read())
	arr = sorted(list(map(int, read().split())))
	avg = 2 * (sum(arr) / len(arr))
	arr = Counter(arr)
	ans = 0
	for num in arr:
		if num == avg - num:
			ans += arr[num] * (arr[num] - 1) // 2
			arr[num] = 0
		elif avg - num in arr:
			ans += arr[num] * arr[avg - num]
			arr[avg - num] = 0
	print(ans)


def solve():
	n = int(input())
	arr = [int(i) for i in input().split()]
	s = sum(arr)
	ss = 2 * s / n
	if not ss.is_integer():
		print(0)
		return
	ss = int(ss)
	c_map = {}
	for i in arr:
		if i not in c_map:
			c_map[i] = 0
		c_map[i] += 1
	count = 0
	for (i, j) in c_map.items():
		if ss - i in c_map:
			if ss - i == i:
				count += j * (j - 1)
			else:
				count += j * c_map[ss - i]
	print(int(count / 2))
t = int(input())
for i in range(t):
	solve()


from math import ceil, floor
from collections import defaultdict
test = int(input())
for t in range(test):
	n = int(input())
	arr = list(map(int, input().split()))
	S = sum(arr) / n
	if ceil(2 * S) != floor(2 * S):
		print(0)
		continue
	S = floor(2 * S)
	mp = defaultdict(int)
	cnt = 0
	for i in range(n):
		if S - arr[i] in mp:
			cnt += mp[S - arr[i]]
		mp[arr[i]] += 1
	print(cnt)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	s = input().split()
	arr = [int(c) for c in s]
	total = sum(arr)
	arr.sort()
	cnt = 0
	cnts = Counter()
	for num in arr:
		pre = 2 * total / n - num
		cnt += cnts[pre]
		cnts[num] += 1
	print(cnt)


def getcount(arr, n, sum):
	m = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in m:
			count += m[sum - arr[i]]
		if arr[i] in m:
			m[arr[i]] += 1
		else:
			m[arr[i]] = 1
	return count
for x in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	s = sum(arr)
	avg = s / n
	df = s - avg * (n - 2)
	ans = getcount(arr, n, df)
	print(ans)


import os, 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))
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
mod = int(1000000000.0 + 7)
from collections import defaultdict as dd
from itertools import combinations

def getPairsCount(arr, n, sum):
	m = dd(int)
	for i in range(0, n):
		m[arr[i]] += 1
	twice_count = 0
	for i in range(0, n):
		twice_count += m[sum - arr[i]]
		if sum - arr[i] == arr[i]:
			twice_count -= 1
	return int(twice_count / 2)
for _ in range(ii1()):
	n = ii1()
	arr = iia()
	k = sum(arr) / n
	if 2 * k == int(2 * k):
		ans = getPairsCount(arr, n, int(2 * k))
		print(ans)
	else:
		print(0)


def solve(n, ls):
	s = sum(ls)
	if 2 * s % n != 0:
		return 0
	rs = 2 * s // n
	i = 0
	j = n - 1
	ans = 0
	ls.sort()
	while i < j:
		ts = ls[i] + ls[j]
		if ts == rs:
			if ls[i] == ls[j]:
				ni = j - i + 1
				ans += ni * (ni - 1) // 2
				break
			c1 = 1
			k = i + 1
			while k < j and ls[k] == ls[i]:
				k += 1
				c1 += 1
			c2 = 1
			l = j - 1
			while l >= k and ls[l] == ls[j]:
				l -= 1
				c2 += 1
			ans += c1 * c2
			i = k
			j = l
			continue
		if ts < rs:
			i += 1
			continue
		j -= 1
		continue
	return ans
t = int(input().strip())
inputs = []
for _ in range(t):
	n = int(input().strip())
	ls = list(map(int, input().strip().split()))
	inputs.append((n, ls))
for (n, ls) in inputs:
	print(solve(n, ls))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	k = 2 * s / n
	d = {}
	r = 0
	for x in a:
		r += d.get(k - x, 0)
		d[x] = d.get(x, 0) + 1
	print(r)


def delete_two_elements(a, n):
	total = 0
	counts_by_ai = {}
	for ai in a:
		total += ai
		if ai in counts_by_ai:
			counts_by_ai[ai] += 1
		else:
			counts_by_ai[ai] = 1
	b = 2 * total // n
	if b * n != 2 * total:
		return 0
	count = 0
	for ai in sorted(counts_by_ai.keys()):
		if 2 * ai < b:
			count += counts_by_ai[ai] * counts_by_ai.get(b - ai, 0)
		elif 2 * ai == b:
			count += counts_by_ai[ai] * (counts_by_ai[ai] - 1) // 2
	return count
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	print(delete_two_elements(a, n))


from collections import defaultdict

def twoSum(a_list, target):
	res = 0
	candi = defaultdict(int)
	for num in a_list:
		if num in candi:
			res += candi[num]
		candi[target - num] += 1
	return res
n_case = int(input())
for _ in range(n_case):
	n = int(input())
	a_list = list(map(int, input().split(' ')))
	avg = sum(a_list) * 2 / n
	if int(avg) != avg:
		print(0)
	else:
		print(twoSum(a_list, avg))


from collections import defaultdict
tests = int(input())
for testcase in range(tests):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	d = defaultdict(int)
	if 2 * s % n:
		print(0)
	else:
		ans = 0
		for e in a:
			d[e] += 1
		x = 2 * s / n
		for e in a:
			f = x - e
			if d[f]:
				ans += d[f]
			if e == f:
				ans -= 1
		print(ans // 2)


def mgc(a, n):
	x = 2 * sum(a) / n
	mp = {}
	ans = 0
	for i in a:
		if x - i in mp:
			ans += mp[x - i]
		if i in mp:
			mp[i] += 1
		else:
			mp[i] = 1
	return ans
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	print(mgc(a, n))


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
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 yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
t = int(input())
for i in range(t):
	dicta = defaultdict(int)
	n = int(input())
	l = list(map(int, input().split()))
	meana = sum(l) / n
	counter = 0
	for i in range(n):
		counter += dicta[2 * meana - l[i]]
		dicta[l[i]] += 1
	print(counter)


def getPairsCount(arr, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in unordered_map:
			count += unordered_map[sum - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return count
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = 2 * sum(arr)
	for i in range(n):
		arr[i] *= n
	ans = getPairsCount(arr, n, temp)
	print(ans)


def getPairsCount(arr, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in unordered_map:
			count += unordered_map[sum - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return count
for i in range(int(input())):
	n = int(input())
	a = list(map(float, input().split()))
	s = sum(a) / n
	summ = float(sum(a) - s * (n - 2))
	print(getPairsCount(a, n, summ))


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	r1 = sum(s) * 2
	s1 = Counter(s)
	s2 = sorted(s1.keys())
	a1 = 0
	a2 = len(s2) - 1
	r = 0
	while a1 <= a2:
		if (s2[a1] + s2[a2]) * n == r1:
			if a1 == a2:
				if s1[s2[a1]] > 1:
					r += s1[s2[a1]] * (s1[s2[a1]] - 1) / 2
			else:
				r += s1[s2[a1]] * s1[s2[a2]]
			a1 += 1
			a2 -= 1
		elif (s2[a1] + s2[a2]) * n > r1:
			a2 -= 1
		else:
			a1 += 1
	print(int(r))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	s = sum(arr)
	ns = s * (n - 2) / n
	rs = s - ns
	c = 0
	hmap = {}
	for i in arr:
		a = rs - i
		if a in hmap:
			c += hmap[a]
		hmap[i] = hmap.get(i, 0) + 1
	print(c)


import operator
import bisect
import math
from queue import PriorityQueue as pq
from heapq import heapify, heappop, heappush, heappushpop, nlargest, heapreplace, nsmallest
from itertools import permutations, accumulate
import os
import array
import sys
from io import BytesIO, IOBase
from collections import Counter, deque, OrderedDict, defaultdict
from bisect import bisect_right, insort_right
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')
getint = lambda : int(sys.stdin.readline().rstrip('\r\n'))
getints = lambda : map(int, sys.stdin.readline().rstrip('\r\n').split())
li = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
getstrs = lambda : map(str, sys.stdin.readline().rstrip('\r\n').split())
ls = lambda : list(map(str, sys.stdin.readline().rstrip('\r\n').split()))

def prog_name():
	n = getint()
	l = li()
	mean = sum(l) / n
	c = Counter(l)
	cnt = 0
	for x in c:
		if 2 * mean - x in c:
			if x == 2 * mean - x:
				cnt += c[x] * (c[x] - 1) // 2
				c[x] = c[2 * mean - x] = 0
			else:
				cnt += c[x] * c[2 * mean - x]
				c[x] = c[2 * mean - x] = 0
	print(cnt)

def main():
	T = getint()
	for unique in range(T):
		prog_name()
main()


def cast(cre, typ):
	return type(typ)(map(cre, typ))

def inp_lis(cre):
	if cre == str:
		return input().split()
	elif cre == bool:
		return cast(bool, cast(int, input().split()))
	else:
		return cast(cre, input().split())

def repl(s, i=-1, ch=''):
	return s[:i] + ch + s[(len(s) + i) % len(s) + 1:]

def solution():
	for t in range(int(input())):
		n = int(input())
		arr = inp_lis(int)
		avg2x = sum(arr) / n * 2
		dic = {}
		ans = 0
		(k, v) = (0, 1)
		for i in range(n):
			if arr[i] in dic:
				dic[arr[i]] += 1
			else:
				dic[arr[i]] = 1
		dic_sorted_keys = sorted(dic.keys())
		idx = 0
		while len(dic_sorted_keys) > idx:
			if avg2x - dic_sorted_keys[idx] in dic:
				if dic_sorted_keys[idx] == avg2x - dic_sorted_keys[idx]:
					n = dic[dic_sorted_keys[idx]] - 1
					ans += (n * n + n) / 2
					del dic[dic_sorted_keys[idx]]
				else:
					ans += dic[dic_sorted_keys[idx]] * dic[avg2x - dic_sorted_keys[idx]]
					del dic[dic_sorted_keys[idx]]
					del dic[avg2x - dic_sorted_keys[idx]]
			idx += 1
		else:
			print(int(ans))
	return
solution()


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
from array import *
import random
M = 10 ** 9 + 7
import heapq
import bisect
from functools import lru_cache
from queue import PriorityQueue
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 binarySearch(arr, n, key):
	left = 0
	right = n - 1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] == key:
			return mid
		if arr[mid] <= key:
			left = mid + 1
		else:
			right = mid - 1
	return -1

def sumofdigits(n):
	n = str(n)
	s1 = 0
	for i in n:
		s1 += int(i)
	return s1

def perfect_square(n):
	s = math.sqrt(n)
	if s == int(s):
		return True
	return False

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 nge(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 find_shortest_path(graph, start, end, path):
	path = path + [start]
	if start == end:
		return path
	if start not in graph:
		return None
	shortest = None
	for node in graph[start]:
		if node not in path:
			newpath = find_shortest_path(graph, node, end, path)
			if newpath:
				if not shortest or len(newpath) < len(shortest):
					shortest = newpath
	return shortest

def test(n, d):
	a = random.randint(1, n - 2)
	p = pow(a, d, n)
	if p == 1 or p == n - 1:
		return True
	while d != n - 1:
		d *= 2
		p = pow(p, 2, n)
		if p == n - 1:
			return True
	return False

def isprime(n):
	if n == 1:
		return False
	if n == 2:
		return True
	if n == 3:
		return True
	d = n - 1
	while d % 2 == 0:
		d //= 2
	for i in range(5):
		if test(n, d) == False:
			return False
	return True

def muin(a, m):
	(x, y, mo) = (1, 0, m)
	if m == 1:
		return 0
	while m > 0:
		(x, y) = (y, x - a // m * y)
		(a, m) = (m, a % m)
	if x < 0:
		return mo + x
	else:
		return x

def good(l, c):
	ch = chr(c)
	if len(l) == 1:
		return 1 if ch != l[0] else 0
	k = len(l) // 2
	lm = k - l[:k].count(ch) + good(l[k:], c + 1)
	rm = k - l[k:].count(ch) + good(l[:k], c + 1)
	return min(lm, rm)

def facto(fact):
	(fact[0], fact[1]) = (1, 1)
	for i in range(2, 10 ** 6 + 1):
		fact[i] = fact[i - 1] * i % M

def comb(n, r, fact):
	return fact[n] * pow(fact[n - r] * fact[r], M - 2, M) % M

def numberToBase(n, b):
	if n == 0:
		return 0
	digits = []
	while n:
		digits.append(n % b)
		n //= b
	return sum(digits)

def getp(arr, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in unordered_map:
			count += unordered_map[sum - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return count

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = lis()
		d = defaultdict(int)
		for i in range(n):
			d[arr[i]] += 1
		k = sum(arr) / n
		p = (n - 2) * k
		if p == int(p):
			p = int(p)
		s = sum(arr) - p
		se = set()
		ans = getp(arr, n, s)
		print(ans)
main()


import sys
import math
from bisect import bisect_left
import heapq
from collections import deque
from itertools import product, permutations
import random

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

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

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

def SI():
	return sys.stdin.readline().strip()

def C(n, k, mod):
	return FACT(n, mod) * pow(FACT(k, mod) * FACT(n - k, mod) % mod, mod - 2, mod) % mod

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)
mod = 10 ** 9 + 7
for _ in range(II()):
	n = II()
	a = LI()
	k = sum(a) / len(a)
	d = {}
	for i in range(n):
		if d.get(a[i]):
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	a = sorted(list(set(a)))
	ans = 0
	for i in range(len(a)):
		if a[i] >= k:
			break
		if d.get(k + (k - a[i])):
			ans += d[a[i]] * d[k + k - a[i]]
	if d.get(k):
		ans += d[k] * (d[k] - 1) // 2
	print(ans)


t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	arr = []
	res = 0
	dict = {}
	arr = list(map(int, input().split()))
	for i in range(0, n):
		res += arr[i]
	res = res * 2
	if res % n != 0:
		print(0)
	else:
		res = int(res / n)
		num = 0
		for i in range(0, n):
			x = res - arr[i]
			temp = dict.get(x, 0)
			num += temp
			temp1 = dict.get(arr[i], 0)
			dict[arr[i]] = temp1 + 1
		print(num)


import sys
input = sys.stdin.buffer.readline
from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	ave = 0
	if s * 2 % n == 0:
		ave = s * 2 // n
	else:
		print(0)
		continue
	c = Counter(a)
	d = dict(c)
	ans = 0
	for key in d:
		if d.get(ave - key) is None:
			continue
		if ave - key == key:
			ans += d[key] * (d[key] - 1)
		else:
			ans += d[key] * d[ave - key]
	print(ans // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	x = sum(l) * 2 / n
	d = {}
	for i in range(n):
		if d.get(l[i], 0) == 0:
			d[l[i]] = 1
		else:
			d[l[i]] += 1
	c = 0
	for i in range(n):
		z = x - l[i]
		if d.get(z, 0) != 0:
			d[l[i]] -= 1
			c += d[z]
	print(c)


t = int(input())
for _ in range(t):
	res = {}
	s = 0
	n = int(input())
	arr = list(map(int, input().split()))
	k = sum(arr) * 2
	if k % n:
		print(0)
		continue
	k //= n
	for i in arr:
		e = k - i
		if e < 0:
			continue
		s += res.get(e, 0)
		res[i] = res.get(i, 0) + 1
	print(s)


def bs(arr, l, r, x):
	if r >= l:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return bs(arr, l, mid - 1, x)
		else:
			return bs(arr, mid + 1, r, x)
	else:
		return -1
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	am = 0
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
		am += i
	am /= n
	ans = 0
	for i in a:
		d[i] -= 1
		search = 2 * am - i
		if search in d:
			ans += d[search]
	print(ans)


def solve():
	n = int(input())
	try:
		arr = list(map(int, input().split()))
		sm = sum(arr)
		ans = 0
		avg = float(sm / n) * 2
		temp = dict()
		for i in range(n):
			if avg - arr[i] in temp:
				ans += temp[avg - arr[i]]
			if arr[i] in temp:
				temp[arr[i]] += 1
			else:
				temp[arr[i]] = 1
		print(ans)
	except EOFError as e:
		print('Error')
for case in range(int(input())):
	solve()


from collections import defaultdict
import sys
input = sys.stdin.readline

def solve(nums):
	n = len(nums)
	sum_ = sum(nums)
	nm = sum_ / n
	esum_ = nm * (n - 2)
	diff = sum_ - esum_
	count = 0
	c = defaultdict(int)
	for i in nums:
		x = diff - i
		if x in c:
			count += c[x]
		c[i] += 1
	print(count)
t = int(input())
for _ in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	solve(nums)


t = int(input())

def sol():
	n = int(input())
	arr = list(map(int, input().split()))
	if 2 * sum(arr) % n != 0:
		return 0
	x = 2 * sum(arr) // n
	arr.sort()
	d = {}
	for i in range(n):
		if arr[i] in d:
			d[arr[i]] += 1
		else:
			d[arr[i]] = 1
	s = 0
	for i in range(n):
		d[arr[i]] -= 1
		if x - arr[i] in d:
			s += d[x - arr[i]]
	return s
for _ in range(t):
	print(sol())


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	sum_ = sum(a)
	p = 2 * sum_
	if p % n != 0:
		print(0)
		continue
	s = sum_ * 2 // n
	m = {}
	for i in range(n):
		if a[i] not in m.keys():
			m[a[i]] = 1
		else:
			m[a[i]] += 1
	count = 0
	t = max(a)
	for i in range(n):
		p = s - a[i]
		if p < 0 or p > t:
			continue
		if p in m.keys():
			count += m[p]
		if p == a[i]:
			count -= 1
	print(count // 2)


from collections import deque, defaultdict, Counter
from itertools import product, groupby, permutations, combinations, accumulate, zip_longest, combinations_with_replacement
from math import gcd, floor, inf, log2, sqrt, log10, factorial
from bisect import bisect_right, bisect_left, insort_left
from statistics import mode
from string import ascii_lowercase, ascii_uppercase
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, nlargest, nsmallest, merge
from copy import deepcopy
from random import shuffle
cases = int(input())
for _ in range(cases):
	num = int(input())
	arr = list(map(int, input().split()))
	freq = Counter(arr)
	mean = 2 * sum(arr) / num
	count = defaultdict(int)
	seen = set()
	used = set()
	cnt = 0
	ans = 0
	for n in arr:
		needed = mean - n
		if needed in seen:
			if needed not in used and n not in used:
				if needed == n:
					temp = freq[needed]
					ans += temp * (temp - 1) // 2
				else:
					ans += freq[needed] * freq[n]
				used.add(n)
				used.add(needed)
		seen.add(n)
	print(ans)


from sys import stdin
import collections, heapq, bisect, math
input = stdin.readline

def rint():
	return int(input())

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

def rlstr():
	return list(input().strip().split())

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

def main():
	n = rint()
	arr = rlint()
	s = sum(arr)
	if 2 * s % n != 0:
		print(0)
		return
	req = 2 * s // n
	res = 0
	has = collections.defaultdict(int)
	for i in range(n):
		res += has[req - arr[i]]
		has[arr[i]] += 1
	print(res)
for _ in range(rint()):
	main()


t = int(input())

def solve():
	n = int(input())
	arr = list(map(int, input().split()))
	avg = sum(arr) / n
	target = avg + avg
	d = dict()
	ans = 0
	for i in arr:
		comp = target - i
		if comp in d.keys():
			ans += d[comp]
		if i not in d.keys():
			d[i] = 1
		else:
			d[i] += 1
	print(ans)
for i in range(t):
	solve()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	target = 2 * sum(arr) / n
	d = {}
	ans = 0
	for el in arr:
		if target - el in d:
			ans += d[target - el]
		if el not in d:
			d[el] = 0
		d[el] += 1
	print(ans)


import sys
import bisect
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	s = sum(arr)
	if s * 2 % n != 0:
		print(0)
	else:
		cnt = 0
		arr.sort()
		m = s * 2 // n
		for i in range(n):
			if 2 * arr[i] < m:
				cnt += bisect.bisect_right(arr, m - arr[i]) - bisect.bisect_left(arr, m - arr[i])
			elif 2 * arr[i] == m:
				k = bisect.bisect_right(arr, m - arr[i]) - bisect.bisect_left(arr, m - arr[i])
				if k >= 2:
					cnt += k * (k - 1) // 2
				break
			else:
				break
		print(cnt)


n = int(input())
for e in range(n):
	n1 = int(input())
	l1 = list(map(int, input().split()))
	q = sum(l1) / len(l1)
	q2 = q * 2
	if q2 - int(q2) != 0:
		print(0)
	else:
		q2 = int(q2)
		h = {}
		c = 0
		for i in range(len(l1)):
			x = q2 - l1[i]
			if x in h:
				c += h[x]
			if l1[i] in h:
				h[l1[i]] += 1
			else:
				h[l1[i]] = 1
		print(c)


def nC2(n):
	return n * (n - 1) // 2
t = int(input())
for _ in range(t):
	n = int(input())
	numbers = list(map(int, input().split()))
	numbers.sort()
	double_mean = 2 * sum(numbers) / n
	count = 0
	left_ptr = 0
	right_ptr = n - 1
	while left_ptr < right_ptr:
		left_num = numbers[left_ptr]
		right_num = numbers[right_ptr]
		if left_num + right_num == double_mean:
			if left_num == right_num:
				count += nC2(right_ptr - left_ptr + 1)
				break
			left_same = 1
			right_same = 1
			while numbers[left_ptr] == numbers[left_ptr + 1]:
				left_ptr += 1
				left_same += 1
			left_ptr += 1
			while numbers[right_ptr] == numbers[right_ptr - 1]:
				right_ptr -= 1
				right_same += 1
			right_ptr -= 1
			count += left_same * right_same
		elif left_num + right_num < double_mean:
			left_ptr += 1
		elif left_num + right_num > double_mean:
			right_ptr -= 1
	print(count)


from sys import stdin
from collections import Counter
input = stdin.readline
rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().strip()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
for _ in range(rn()):
	n = rn()
	a = rl()
	s = sum(a)
	b = [n * num - s for num in a]
	c = Counter(b)
	ans = 0
	for i in range(n):
		ndiff = n * a[i] - s
		other = c[-ndiff]
		if ndiff == 0:
			other -= 1
		ans += other
	print(ans // 2)


n = int(input())
for i in range(n):
	(count, d, s) = (0, {}, int(input()))
	l = list(map(int, input().split()))
	k = 2 * sum(l) / s
	for x in l:
		if x not in d:
			d[x] = 0
		d[x] += 1
	if k != int(k):
		print('0')
	else:
		p = int(k / 2)
		for i in d.keys():
			if i < p:
				try:
					count += d[i] * d[k - i]
				except KeyError:
					pass
			elif i == p:
				if k % 2 == 0:
					for m in range(d[i]):
						count += m
				else:
					try:
						count += d[i] * d[i + 1]
					except KeyError:
						pass
		print(count)


import heapq
import sys
from math import *
import threading
from heapq import *
from itertools import count
from pprint import pprint
from collections import defaultdict
from heapq import heapify, heappop, heappush
mod = 10 ** 9 + 7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
import os
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')

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 npr(self, n, k):
		if k < 0 or n < k:
			return 0
		f = self.factorial
		return f.calc(n) * f.invFactorial(n - k) % self.MOD

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)

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

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

def binary_search(li, val):
	ans = -1
	lb = 0
	ub = len(li) - 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 pref(li):
	pref_sum = [li[0]]
	for i in range(1, len(li)):
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [{1, i} for i in range(n + 1)]
	p = 2
	while p <= n:
		for i in range(p * 2, n + 1, p):
			prime[i].add(p)
		p += 1
	return prime

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 prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def given():
	a = list(map(int, input().split()))
	return a

def givenStringList():
	s = list(input())
	return s

def givenStringListInt():
	s = [int(x) for x in givenStringList()]
	return s

def main():
	karmanya = given()[0]
	while karmanya != 0:
		karmanya -= 1
		n = given()[0]
		a = sorted(given())
		d = defaultdict(int)
		for i in a:
			d[i] += 1
		sumi = sum(a)
		mean = sumi / n
		sumi = sumi - mean * (n - 2)
		ans = d[sumi / 2] * (d[sumi / 2] - 1) // 2
		for i in set(a):
			if i != sumi / 2 and i < sumi - i:
				ans += d[i] * d[sumi - i]
		print(ans)
main()


from sys import stdin, stdout, setrecursionlimit
from io import BytesIO, IOBase
from collections import Counter, deque, defaultdict
setrecursionlimit(10000)

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:
			a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not a:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = a.count(b'\n') + (not a)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(a), 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')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))
input = lambda : stdin.readline().rstrip('\r\n')
inp = lambda : int(input())
st = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
int_arr = lambda : list(map(int, input().strip().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().strip().split())
get_int = lambda : map(int, input().strip().split())
get_float = lambda : map(float, input().strip().split())
mod = 1000000007
for _ in range(inp()):
	n = inp()
	a = int_arr()
	f = 0
	s = sum(a)
	m = defaultdict(int)
	t = 2 * s
	if t % n == 0:
		t = t // n
	else:
		f = 1
		print(0)
	if f == 0:
		res = 0
		for i in range(n):
			if m[t - a[i]] > 0:
				res += m[t - a[i]]
			m[a[i]] += 1
		print(res)


def solve():
	n = int(input())
	seq = list(map(int, input().split()))
	res = sum(seq) * (n - 2)
	if res % n != 0:
		print(0)
	else:
		k = sum(seq) - res // n
		freq = {x: 0 for x in seq}
		freq.update({k - x: 0 for x in seq})
		for x in seq:
			freq[x] += 1
		ans = 0
		for x in seq:
			freq[x] -= 1
			ans += freq[k - x]
		print(ans)
[solve() for _ in range(int(input()))]


from collections import defaultdict

def getp(array1, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - array1[i] in unordered_map:
			count += unordered_map[sum - array1[i]]
		if array1[i] in unordered_map:
			unordered_map[array1[i]] += 1
		else:
			unordered_map[array1[i]] = 1
	return count

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		n = int(input())
		array1 = list(map(int, input().split()))
		d = defaultdict(int)
		for i in range(n):
			d[array1[i]] += 1
		k = sum(array1) / n
		p = (n - 2) * k
		if p == int(p):
			p = int(p)
		s = sum(array1) - p
		se = set()
		ans = getp(array1, n, s)
		print(ans)
main()


from collections import defaultdict
t = int(input())
for x in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	k = sum(a) - (n - 2) * sum(a) / n
	d = defaultdict(lambda : 0)
	count = 0
	for i in a:
		if k - i in d:
			count += d[k - i]
		d[i] += 1
	print(count)


t = int(input())
for test in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	org_sum = sum(p)
	mean = org_sum / n
	diff = org_sum - mean * (n - 2)
	if diff % 1 != 0:
		print(0)
		continue
	ans = [0] * len(p)
	dist = {}
	for (ind, i) in enumerate(p):
		if i not in dist:
			dist[i] = 1
		else:
			dist[i] += 1
		if diff - i in dist:
			ans[ind] -= dist[diff - i]
	for (ind, i) in enumerate(p):
		if diff - i in dist:
			ans[ind] += dist[diff - i]
	res = 0
	for i in ans:
		if i > 0:
			res += i
	print(res)


def pop_ct(s):
	t = s
	ct = 0
	while t > 0:
		if t & 1:
			ct += 1
		t >>= 1
	return ct
from collections import defaultdict as dft
for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().split()))
	S = sum(A)
	B = [a * N - S for a in A]
	ct = dft(int)
	for b in B:
		ct[b] += 1
	ans = 0
	for (c, v) in ct.items():
		if -c not in ct:
			continue
		if c == 0:
			ans += v * (v - 1)
		else:
			ans += v * ct[-c]
	print(ans // 2)


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	l.sort()
	(i, j) = (0, n - 1)
	k = sum(l) / n * 2
	r = 0
	while i < j:
		if l[i] + l[j] == k:
			if l[i] == l[j]:
				r += (j - i + 1) * (j - i) // 2
				break
			else:
				ci = 1
				cj = 1
				while l[i] == l[i + 1]:
					i += 1
					ci += 1
				while l[j] == l[j - 1]:
					j -= 1
					cj += 1
				r += ci * cj
			i += 1
			j -= 1
		elif l[i] + l[j] > k:
			j -= 1
		else:
			i += 1
	print(r)


def pairs_count(arr, n, sum):
	ans = 0
	arr = sorted(arr)
	(i, j) = (0, n - 1)
	while i < j:
		if arr[i] + arr[j] < sum:
			i += 1
		elif arr[i] + arr[j] > sum:
			j -= 1
		else:
			x = arr[i]
			xx = i
			while i < j and arr[i] == x:
				i += 1
			y = arr[j]
			yy = j
			while j >= i and arr[j] == y:
				j -= 1
			if x == y:
				temp = i - xx + yy - j - 1
				ans += temp * (temp + 1) // 2
			else:
				ans += (i - xx) * (yy - j)
	return ans
for i in range(int(input())):
	n = int(input())
	a = list(map(float, input().split()))
	s = sum(a) / n
	summ = float(sum(a) - s * (n - 2))
	print(pairs_count(a, n, summ))


from sys import stdin, stdout
ip = lambda : stdin.readline().rstrip('\r\n')
ips = lambda : ip().split()
mp = lambda : map(int, ips())
ls = lambda : list(mp())
out = lambda x, end='\n': stdout.write(f'{x}{end}')
from collections import defaultdict
for _ in range(int(ip())):
	n = int(ip())
	a = ls()
	s = sum(a) * 2
	if s % n != 0:
		out(0)
	else:
		s //= n
		d = defaultdict(int)
		c = 0
		for i in range(n):
			if d.get(s - a[i], -1) != -1:
				c += d[s - a[i]]
			d[a[i]] += 1
		out(c)


def handler(nums):
	mean = sum(nums) / len(nums)
	target = 2 * mean
	dict = {}
	for i in range(len(nums)):
		if dict.get(nums[i]) is not None:
			dict[nums[i]] += 1
		else:
			dict[nums[i]] = 1
	count = 0
	for key in dict:
		if 2 * key <= target:
			if 2 * key == target:
				count += (dict[key] - 1) * dict[key] / 2
			elif target - key in dict:
				count += dict[key] * dict[target - key]
	return count
t = int(input())
for i in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	print(int(handler(nums)))


def cnt(arr, n, summ):
	count = 0
	mdict = {}
	for i in range(n):
		if summ - arr[i] in mdict:
			count += mdict[summ - arr[i]]
		if arr[i] in mdict:
			mdict[arr[i]] += 1
		else:
			mdict[arr[i]] = 1
	print(count)
for _ in range(int(input())):
	n = int(input())
	grid = list(map(int, input().split()))
	res = 2 * sum(grid) / n
	cnt(grid, n, res)


from collections import Counter
from fractions import Fraction
for _ in range(int(input())):
	n = int(input())
	counts = Counter(map(int, input().split()))
	(total_sum, n) = (0, 0)
	for (v, t) in counts.items():
		total_sum += v * t
		n += t
	mean = Fraction(total_sum, n)
	(u, p) = (0, 0)
	ans = 0
	for value in counts:
		req_value = -(mean * (n - 2) - (total_sum - value))
		if req_value not in counts:
			continue
		if req_value == value:
			x = counts[value]
			u += x * (x - 1) // 2
		else:
			p += counts[value] * counts[req_value]
	print(u + p // 2)


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 collections import defaultdict, deque
from math import ceil, floor, sqrt, log2, gcd, pi
from heapq import heappush, heappop
from bisect import bisect_left, bisect
from functools import reduce
from copy import deepcopy
import sys
abc = 'abcdefghijklmnopqrstuvwxyz'
ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	s = sum(arr)
	mean = s / n
	news = mean * (n - 2)
	d = defaultdict(int)
	diff = s - news
	ans = 0
	for i in range(n):
		if diff - arr[i] in d:
			ans += d[diff - arr[i]]
		d[arr[i]] += 1
	print(ans)


import sys
from collections import defaultdict

def del_two_element(n, a):
	for i in range(len(a)):
		a[i] = int(a[i])
	n = len(a)
	s = sum(a)
	p = 2 * s // n
	n_pair = 0
	d = defaultdict(lambda : 0)
	if (s - p) * n != s * (n - 2):
		return 0
	for i in a:
		x = p - i
		n_pair += d[x]
		d[i] += 1
	return n_pair
t = int(sys.stdin.readline())
for _ in range(0, t):
	n = map(int, input())
	a = sys.stdin.readline().split()
	print(del_two_element(n, a))


import sys
input = sys.stdin.readline

def main():
	N = int(input())
	A = list(map(int, input().split()))
	D = {}
	for a in A:
		if a in D:
			D[a] += 1
		else:
			D[a] = 1
	S = sum(A)
	if 2 * S % N:
		return print(0)
	B = 2 * S // N
	Ans = 0
	for a in A:
		if B - a in D:
			Ans += D[B - a]
			if B - a == a:
				Ans -= 1
		D[a] -= 1
	print(Ans)
T = int(input())
for _ in range(T):
	main()


def compl(x, k):
	return 2 * k - x

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	s = dict()
	k = 0
	ans = 0
	for i in a:
		k += i
	k = k / n
	if k > int(k) and k - int(k) != 0.5:
		print(0)
		return
	for i in a:
		c = compl(i, k)
		if c in s.keys():
			ans += s[c]
		if i in s.keys():
			s[i] += 1
		else:
			s[i] = 1
	print(ans)
t = int(input())
for i in range(t):
	solve()


import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
output = sys.stdout.write

def solve(N, nums):
	(target, rem) = divmod(2 * sum(nums), N)
	if rem != 0:
		return 0
	res = 0
	cnt = {}
	for num in nums:
		res += cnt.get(target - num, 0)
		cnt[num] = cnt.get(num, 0) + 1
	return res

def main():
	T = int(input())
	for _ in range(T):
		N = int(input())
		nums = list(map(int, input().split()))
		out = solve(N, nums)
		output(str(out) + '\n')
main()


from __future__ import division, print_function
from collections import defaultdict, deque
import heapq
import os
import copy
import sys
from io import BytesIO, IOBase
from typing import Counter, DefaultDict, Deque, OrderedDict
import bisect, math, time
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from math import ceil, log2
MOD = 1000000007

def power(x, y):
	if y == 0:
		return 1
	if x == 0:
		return 0
	temp = power(x, y // 2)
	if y % 2 == 0:
		return temp * temp % MOD
	else:
		return x * temp * temp % MOD

def main():
	t = int(input())
	while t:
		n = int(input())
		a = list(map(int, input().split()))
		sm = sum(a)
		m = sm / n
		ns = m * (n - 2)
		target = sm - ns
		cache = {}
		cnt = 0
		for (v, i) in enumerate(a):
			if i in cache:
				cnt += 1 * cache[i]
			if target - i in cache:
				cache[target - i] += 1
			else:
				cache[target - i] = 1
		print(cnt)
		t -= 1
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 decimal
import heapq
import math
import os
import sys
from collections import Counter, deque
from io import BytesIO, IOBase
import 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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

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

def chars_get():
	return list(map(str, sys.stdin.readline().strip().split()))

def output(to_be_printed, end='\n'):
	sys.stdout.write(str(to_be_printed) + end)

def ipn():
	return int(input())

def main():
	for _ in range(ipn()):
		n = ipn()
		a = list_get()
		c = Counter(a)
		s = sum(a)
		if n % 2 == 0:
			n //= 2
		else:
			s *= 2
		if s % n != 0:
			output(0)
		else:
			s //= n
			count = 0
			for i in a:
				count += c[s - i]
				if i == s - i:
					count -= 1
			count //= 2
			output(count)
	return
main()


from math import *
from math import factorial as fact, comb as ncr
from bisect import bisect_left as bl
from bisect import bisect_right as br
from array import array
from collections import Counter as ctr
from collections import deque as dq
li = lambda : list(map(int, input().split()))
arr = lambda a: array('i', a)
bi = lambda n: bin(n).replace('0b', '')

def solve():
	for _ in range(int(input())):
		n = int(input())
		a = li()
		pn = {}
		c = 0
		s = 2 * (sum(a) / n)
		if int(s) == s:
			for i in range(n):
				if s - a[i] in pn:
					c += pn[s - a[i]]
				if a[i] in pn:
					pn[a[i]] += 1
				else:
					pn[a[i]] = 1
			print(c)
		else:
			print(0)
solve()


import math
from collections import defaultdict, Counter
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	mean = sum(l) / n
	d = Counter(l)
	cnt = 0
	for k in d.keys():
		if k < mean:
			if 2 * mean - k in d:
				cnt += d[k] * d[2 * mean - k]
	if d[mean] != 0:
		cnt += d[mean] * (d[mean] - 1) // 2
	print(cnt)


from math import ceil, log, floor
from collections import defaultdict, deque
import sys
import os.path
sys.setrecursionlimit(200000)
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r+')
	sys.stdout = open('output.txt', 'w')

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

def MF():
	return map(float, input().split())
mod = 10 ** 9 + 7

def count(arr, n, sum):
	d = defaultdict(int)
	count = 0
	for i in range(n):
		if sum - arr[i] in d:
			count += d[sum - arr[i]]
		d[arr[i]] += 1
	return count

def solve():
	n = int(input())
	a = list(MF())
	m = sum(a) / n
	print(count(a, n, 2 * m))
t = int(input())
for _ in range(t):
	solve()


def delete_2_ints(n: int, a: list):
	sum_of_2_ints = sum(a) * 2 / n
	return count_twoSum(a, sum_of_2_ints)

def count_twoSum(my_list: list, k: int):
	my_map = {}
	for i in my_list:
		if i in my_map:
			my_map[i] += 1
		else:
			my_map[i] = 1
	res = 0
	for i in my_list:
		my_k = k - i
		if my_k == i:
			res += my_map[my_k] - 1
		elif my_k in my_map:
			res += my_map[my_k]
	return int(res / 2)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(delete_2_ints(n, a))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	at = sum(l) * (n - 2) / n
	ls = {}
	for i in l:
		if i in ls:
			ls[i] += 1
		else:
			ls[i] = 1
	ans = 0
	at = sum(l) - at
	for (i, j) in ls.items():
		if at - i in ls:
			if at - i == i:
				ans += j * (j - 1) // 2
				ls[i] = 0
			else:
				ans += j * ls[at - i]
				ls[i] = 0
				ls[at - i] = 0
	print(ans)


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
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')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

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

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

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

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	n = ii()
	l = li()
	s = sum(l)
	if 2 * s % n != 0:
		print(0)
		return
	reqSum = 2 * s // n
	d = defaultdict(lambda : 0)
	ans = 0
	for i in l:
		x = reqSum - i
		ans += d[x]
		d[i] += 1
	print(ans)
t = 1
t = ii()
for _ in range(t):
	solve()


def process(A):
	S = sum(A)
	n = len(A)
	d = {}
	if 2 * S % n != 0:
		return 0
	M = 2 * S // n
	for i in range(n):
		x = A[i]
		if x not in d:
			d[x] = 0
		d[x] += 1
	answer = 0
	for x in d:
		if M - x in d:
			if x < M - x:
				answer += d[x] * d[M - x]
			elif x == M - x:
				answer += d[x] * (d[x] - 1) // 2
	return answer
t = int(input())
for i in range(t):
	n = int(input())
	A = [int(x) for x in input().split()]
	print(process(A))


import sys
LI = lambda : list(map(int, sys.stdin.readline().split()))
MI = lambda : map(int, sys.stdin.readline().split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline())
for _ in range(II()):
	n = II()
	a = LI()
	cnt = {}
	for v in a:
		cnt[v] = cnt.get(v, 0) + 1
	s = sum(a)
	avg = s / n
	s1 = avg * (n - 2)
	ans = 0
	for v in a:
		x = s - s1 - v
		ans += cnt.get(x, 0) - (v == x)
	print(ans // 2)


for s in [*open(0)][2::2]:
	a = (*map(int, s.split()),)
	k = 2 * sum(a) / len(a)
	d = {}
	r = 0
	for x in a:
		r += d.get(k - x, 0)
		d[x] = d.get(x, 0) + 1
	print(r)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a) / n
	c = Counter()
	d = 0
	for i in a:
		d += c[2 * s - i]
		c[i] += 1
	print(d)


from typing import Counter, DefaultDict

def solve(n, arr):
	tot = sum(arr)
	m = tot / n
	new_tot = (n - 2) * tot / n
	diff = tot - new_tot
	res = 0
	equals = set()
	arrSet = DefaultDict(int)
	for i in arr:
		rem = diff - i
		if rem in arrSet:
			res += arrSet[rem]
		arrSet[i] += 1
	print(f'{res}')
	return

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(n, arr)
main()


def getPairsCount(arr, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in unordered_map:
			count += unordered_map[sum - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return count
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	ave = s / n * 2
	if int(ave) != ave:
		print(0)
	else:
		co = getPairsCount(a, n, int(ave))
		print(co)


from math import *
from collections import defaultdict as dt
from sys import stdin
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	n = I()
	b = L()
	d = dt(int)
	y = 2 * (sum(b) / n)
	a = []
	for i in b:
		d[i] += 1
		if d[i] == 1:
			a.append(i)
	a.sort()
	i = 0
	j = len(a) - 1
	c = 0
	while i < j:
		x = a[i] + a[j]
		if x == y:
			c = c + d[a[i]] * d[a[j]]
			i = i + 1
		elif x < y:
			i = i + 1
		else:
			j = j - 1
	y = y / 2
	print(c + d[y] * (d[y] - 1) // 2)
tt = 1
tt = I()
for _ in range(tt):
	solve()


import bisect
_ = int(input())
for __ in range(_):
	n = int(input())
	arr = sorted(list(map(int, input().split())))
	avg = sum(arr) / n
	out = 0
	if int(avg * 2) != avg * 2:
		print('0')
		continue
	pairs = 0
	for x in arr:
		s = int(avg * 2 - x)
		if s < 0:
			break
		pos_l = bisect.bisect_left(arr, s)
		pos_r = bisect.bisect_right(arr, s)
		d = pos_r - pos_l
		if s == x:
			d -= 1
		out += d
	print(out // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = 1
		else:
			d[a[i]] += 1
	c = 0
	s = sum(a)
	if 2 * s % n == 0:
		for i in range(n):
			k = 2 * s // n - a[i]
			if k in d:
				c = c + d[k] if a[i] != k else c + d[k] - 1
		print(c // 2)
	else:
		print(0)


from math import factorial
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	av = sum(s) / n
	AV2 = av * 2
	d = dict()
	ans = 0
	for i in range(n):
		ans += d.get(AV2 - s[i], 0)
		d[s[i]] = d.get(s[i], 0) + 1
	print(ans)


import sys
import os
from math import ceil, floor, sqrt, gcd, factorial, log, log2
from io import BytesIO, IOBase
from collections import Counter
from itertools import permutations, combinations
from bisect import bisect
from functools import reduce
inf = int(10000000000.0)
BUFSIZE = 8192
inp = lambda : int(input())
mp = lambda : map(int, input().split())
lst = lambda : list(map(int, input().split()))

def main():
	for _ in range(inp()):
		n = inp()
		a = lst()
		m = sum(a) / n
		c = Counter(a)
		ans = 0
		for i in c:
			j = 2 * m - i
			if j in c:
				if i == j:
					ans += c[i] * (c[i] - 1) // 2
					c[i] = c[j] = 0
				else:
					ans += c[i] * c[j]
					c[i] = c[j] = 0
		print(ans)

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()


import heapq
import math
import sys
import collections
import bisect
import time
import random
import itertools
import string
from collections import Counter, defaultdict

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

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

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	n = int(input())
	arr = get_list()
	mean = sum(arr) / n
	two_sum = 2 * mean
	ts1 = math.floor(two_sum)
	ts2 = math.ceil(two_sum)
	counter = collections.Counter(arr)
	ans = 0
	for i in counter:
		diff1 = ts1 - i
		diff2 = ts2 - i
		if diff1 == diff2 and diff1 in counter:
			if diff1 == i:
				ans += counter[i] * (counter[i] - 1)
			else:
				ans += counter[i] * counter[diff1]
	print(ans // 2)


import os, sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		su = sum(a)
		if su * (n - 2) % n:
			print(0)
			continue
		su1 = su * (n - 2) // n
		de = su - su1
		x = Counter(a)
		ans = 0
		for i in x:
			req = de - i
			if req == i:
				ans += x[i] * (x[i] - 1) // 2
			elif req < i:
				ans += x[i] * x[req]
		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()


def solve(n, a):
	s2 = sum(a) * 2
	if s2 % n:
		return 0
	target = s2 // n
	d = {}
	res = 0
	for v in a:
		diff = target - v
		count = d.get(diff, 0)
		res += count
		count = d.get(v, 0)
		d[v] = count + 1
	return res
t = int(input())
for i_t in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	print(solve(n, a))


t = int(input())
for tc in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	newarr = {}
	for i in range(n):
		try:
			newarr[arr[i] * n] += 1
		except:
			newarr[arr[i] * n] = 1
	s = sum(arr)
	ans = 0
	for num in arr:
		newarr[num * n] -= 1
		x = 2 * s - num * n
		try:
			if newarr[x]:
				ans += newarr[x]
		except:
			pass
	print(ans)


import collections
import sys

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

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

def input():
	return sys.stdin.readline().strip()
MOD = 1000000007
for _ in range(int(input())):
	n = int(input())
	arr = get_array()
	x = sum(arr)
	y = x - 2 * x / n
	k = sum(arr) / n
	c = collections.Counter(arr)
	cnt = 0
	for i in range(n):
		c[arr[i]] -= 1
		cnt += c.get(2 * k - arr[i], 0)
	print(cnt)


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	counts = defaultdict(int)
	avg = sum(arr) / n
	for x in arr:
		counts[x] += 1
	ans = 0
	for x in {x for x in arr if x < avg}:
		ans += counts[x] * counts[2 * avg - x]
	ans += counts[avg] * (counts[avg] - 1) // 2
	print(ans)


from collections import deque
from collections import OrderedDict
import queue
import heapq
import math
from re import I
import sys
sys.setrecursionlimit(10 ** 6)

def sf():
	return [int(x) for x in input().split(' ')]

def sfi():
	return int(input())

def sfs():
	return input()

def printf(x):
	print(x)
	sys.stdout.flush()

def main():
	t = sfi()
	for tc in range(t):
		fr = {}
		n = sfi()
		ls = sf()
		sm = sum(ls) << 1
		if sm % len(ls):
			print('0')
			continue
		tot = int(sm / len(ls))
		res = 0
		for i in ls:
			x = tot - i
			if x in fr:
				res += fr[x]
			if i in fr:
				fr[i] += 1
			else:
				fr[i] = 1
		print(res)
main()


for _ in range(int(input())):
	n = int(input())
	from collections import defaultdict
	arr = list(map(int, input().split()))
	temp = 2 * sum(arr) / n
	dic = defaultdict(int)
	ans = 0
	for x in arr:
		if temp - x in dic:
			ans += dic[temp - x]
		dic[float(x)] += 1
	print(ans)


def ps_cnt(arr, n, s):
	mapping = {}
	count = 0
	for i in range(n):
		if s - arr[i] in mapping:
			count += mapping[s - arr[i]]
		if arr[i] in mapping:
			mapping[arr[i]] += 1
		else:
			mapping[arr[i]] = 1
	return count
t = int(input())
lens = []
nums = []
for i in range(t):
	l = int(input())
	lens.append(l)
	num = list(map(int, input().strip().split()))[:l]
	nums.append(num)
for i in range(t):
	if lens[i] <= 2:
		print(0)
		continue
	k = sum(nums[i]) / lens[i]
	two_sum = k * 2
	if not two_sum.is_integer():
		print(0)
		continue
	else:
		two_sum = int(two_sum)
	print(ps_cnt(nums[i], len(nums[i]), two_sum))


from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = a[:]
	x = sum(a) / n
	s = 2 * x
	c = 0
	d = defaultdict(lambda : 0)
	for i in a:
		d[i] += 1
	if int(s) != s:
		print(0)
	else:
		for i in range(n):
			d[a[i]] -= 1
			c += d[s - a[i]]
		print(c)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	m = sum(l) / n
	d = {}
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	ans = 0
	for i in d:
		if 2 * m - i == i:
			ans += d[i] * (d[i] - 1)
			continue
		if 2 * m - i in d:
			ans += d[i] * d[2 * m - i]
	print(ans // 2)


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split(' ')))
	s = sum(l)
	x = float(s * 2 / n)
	if not x.is_integer():
		print(0)
		continue
	x = int(x)
	i = 0
	black_list = set()
	c = Counter(l)
	for (v, vv) in c.items():
		w = x - v
		if w == v:
			if vv > 1:
				i += sum(range(vv))
		elif w in c.keys():
			i += c[w] * vv / 2
	print(int(i))


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from itertools import accumulate as ac
from random import randint as ri
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	n = ip()
	arr = list(inp())
	dic = Counter()
	cur = sum(arr)
	ans = 0
	for i in arr:
		num = cur * (n - 2)
		den = n
		if num % den == 0:
			c = num // den
			ele = cur - i - c
			ans += dic[ele]
		dic[i] += 1
	print(ans)


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	acounter = Counter(a)
	k = sum(a) / len(a)
	total = 0
	for number in a[:-1]:
		acounter[number] -= 1
		total += acounter.get(k * 2 - number, 0)
	print(total)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	k = sum(l) / n
	if int(k * 2) != k * 2:
		print(0)
	else:
		d = {}
		ans = 0
		for i in range(n):
			if l[i] - k in d:
				d[l[i] - k] += 1
			else:
				d[l[i] - k] = 1
		for key in d:
			if key == 0:
				ans += d[0] * (d[0] - 1) // 2
			elif key < 0:
				if abs(key) in d:
					ans += d[key] * d[abs(key)]
		print(ans)


import sys
from collections import defaultdict
input = sys.stdin.readline
testcases = int(input())
tests = []
for i in range(testcases):
	input = sys.stdin.readline
	n = int(input())
	input = sys.stdin.readline
	nums = list(map(int, input().split()))
	tests.append(nums)

def deleteTwoElements(nums):
	n = len(nums)
	summation = sum(nums)
	avg = summation / n
	wantedSum = 2 * avg
	hashset = set()
	ways = 0
	count = defaultdict(int)
	for num in nums:
		if num in hashset:
			ways += count[wantedSum - num]
		hashset.add(wantedSum - num)
		count[num] += 1
	return ways
for test in tests:
	print(deleteTwoElements(test))


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(sorted(list(map(int, input().split()))))
	c = []
	for i in range(0, n):
		if i == 0 or l[i - 1] != l[i]:
			c.append([l[i], 1])
		elif l[i - 1] == l[i]:
			c[-1][1] += 1
	s = sum(l) * 2
	n1 = n
	n = len(c)
	p1 = 0
	p2 = n - 1
	ans = 0
	while p1 <= p2:
		while p1 <= p2 and (c[p1][0] + c[p2][0]) * n1 > s:
			p2 -= 1
		if p1 > p2:
			break
		if (c[p1][0] + c[p2][0]) * n1 == s:
			if p1 == p2:
				ans += (c[p1][1] - 1) * c[p1][1] // 2
			else:
				ans += c[p1][1] * c[p2][1]
		p1 += 1
	print(ans)


from typing import Counter
import sys
from collections import defaultdict as dd
from math import *

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

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

def sinp():
	return input()

def inp():
	return int(input())

def mod(f):
	return f % 1000000007

def pr(*x):
	print(*x)

def finp():
	f = open('input.txt', 'r')
	f = f.read().split('\n')
	return f

def finp():
	f = open('input.txt', 'r')
	f = f.read().split('\n')
	return f

def fout():
	return open('output.txt', 'w')

def fpr(f, x):
	f.write(x + '\n')

def csort(c):
	sorted(c.items(), key=lambda pair: pair[1], reverse=True)

def indc(l, n):
	c = {}
	for i in range(n):
		c[l[i]] = c.get(l[i], []) + [i + 1]
	return c

def co(l, n, k):
	temp = {}
	f = 0
	for i in range(n):
		if k - l[i] in temp:
			f += temp[k - l[i]]
		if l[i] in temp:
			temp[l[i]] += 1
		else:
			temp[l[i]] = 1
	return f
cou = inp()
for _ in range(cou):
	n = inp()
	l = linp()
	s = sum(l)
	pr(co(l, n, s - s / n * (n - 2)))


for _ in range(int(input())):
	a = int(input())
	l = list(map(int, input().split()))
	k = sum(l)
	k = k * 2
	if k % a:
		print(0)
	else:
		dic = {}
		k = k // a
		out = 0
		for i in range(a):
			b = k - l[i]
			if b in dic:
				out += dic[b]
			if l[i] not in dic:
				dic[l[i]] = 1
			else:
				dic[l[i]] += 1
		print(out)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
inp_vars_int = lambda : map(int, input().split())
inp_list_int = lambda : list(map(int, input().split()))
t = int(input())
for _ in range(t):
	n = int(input())
	a = inp_list_int()
	cnt = Counter(a)
	res = 0
	k = sum(a) / len(a)
	for num in cnt:
		if num > k:
			res += cnt[num] * cnt[2 * k - num]
	res += cnt[k] * (cnt[k] - 1) // 2
	print(res)


import math
from sys import stdin
input = stdin.readline
test = int(input())
for _ in range(test):
	(n, arr, result) = (int(input()), [], True)
	arr = list(map(int, input().split()))
	k = sum(arr) * 1.0 / len(arr)
	(d, res) = ({}, 0)
	for a in arr:
		if 2 * k - a in d:
			res += d[2 * k - a]
		d[a] = d.get(a, 0) + 1
	print(res)


from collections import deque, defaultdict
from math import sqrt, ceil, factorial, floor, inf, log2, sqrt, gcd
import bisect
import copy
from itertools import combinations
import sys
import heapq

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

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

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	a = get_array()
	tot = sum(a)
	sumi = 2 * tot / n
	d = defaultdict(int)
	for i in range(n):
		d[a[i]] += 1
	ans = 0
	li = list(d.keys())
	for i in range(len(li)):
		num1 = li[i]
		if num1 <= sumi:
			num2 = sumi - num1
			if num1 != num2:
				ans += d[num1] * d[num2]
			else:
				ans += d[num1] * (d[num1] - 1)
	print(ans // 2)


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict()
	for x in a:
		if x in d:
			d[x] += 1
		else:
			d[x] = 1
	s = sum(a)
	if s * (n - 2) % n != 0:
		print(0)
		continue
	else:
		t = s * (n - 2) // n
		ans = 0
		for x in a:
			y = s - t - x
			if x == y:
				ans += d[y] - 1
			elif y in d:
				ans += d[y]
		print(ans // 2)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	avg = sum(arr) / n
	count = dict.fromkeys(arr, 0)
	for x in arr:
		count[x] += 1
	arr = list(set(arr))
	if len(arr) == 1:
		print(n * (n - 1) // 2)
		continue
	arr.sort()
	ans = 0
	(i, j) = (0, len(arr) - 1)
	while i <= j:
		while (arr[i] + arr[j]) / 2 > avg and j > i:
			j -= 1
		if (arr[i] + arr[j]) / 2 == avg and i != j:
			ans += count[arr[i]] * count[arr[j]]
		if i == j and arr[i] == avg:
			l = count[arr[i]]
			ans += l * (l - 1) // 2
		i += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	k = sum(a)
	if 2 * k / n % 1 != 0:
		print(0)
	else:
		ctr = {}
		for i in a:
			if not i in ctr:
				ctr[i] = 0
			ctr[i] += 1
		ans = 0
		for (i, j) in ctr.items():
			if 2 * k // n - i in ctr:
				if n * i == k:
					ans += j * (j - 1)
				else:
					ans += j * ctr[2 * k // n - i]
		print(ans // 2)


import sys
from math import factorial, gcd
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest, nsmallest
from itertools import groupby, accumulate
from copy import deepcopy
MOD = 10 ** 9 + 7
INF = float('inf')
input = sys.stdin.readline
rl = lambda : list(map(int, input().split()))
rs = lambda : sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	A = rl()
	res = 0
	target = sum(A) / n * 2
	if target != int(target):
		print(0)
		continue
	C = Counter()
	for i in range(n):
		res += C[target - A[i]]
		C[A[i]] += 1
	print(res)


from collections import Counter

def solve(a):
	r = sum(a) * 2
	if r % len(a) != 0:
		return 0
	r //= len(a)
	c = Counter(a)
	cc = sorted(c.items())
	res = 0
	for (v, cnt) in cc:
		if v * 2 >= r:
			break
		res += cnt * c[r - v]
	if r % 2 == 0:
		res += c[r // 2] * (c[r // 2] - 1) // 2
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(a))


def main():
	T = int(input())
	for t in range(T):
		print(test())

def test():
	input()
	xs = [int(i) for i in input().split(' ')]
	k = len(xs)
	s = sum(xs)
	p = 2 * s / k
	q = {}
	a = 0
	for x in xs:
		c = p - x
		if c in q:
			a += q[c]
		if x not in q:
			q[x] = 1
		else:
			q[x] += 1
	return a
main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = [int(num) for num in input().split()]
	math_mean = sum(a) / n
	pair_sum = 2 * math_mean
	d = defaultdict(int)
	for a_i in a:
		d[a_i] += 1
	ans = 0
	visited = set()
	for a_i in d:
		if pair_sum - a_i in d and a_i not in visited and (pair_sum - a_i not in visited):
			visited.add(a_i)
			visited.add(pair_sum - a_i)
			if pair_sum - a_i != a_i:
				ans += d[pair_sum - a_i] * d[a_i]
			else:
				ans += d[a_i] * (d[a_i] - 1) // 2
	print(ans)


import collections

def is_equal(a, b):
	return a == b
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	total = sum(arr)
	avg = total / n
	pairs = 0
	if is_equal(avg, (total - 2 * avg) / (n - 2)):
		target = avg * 2
		ctr = collections.Counter(arr)
		for el in ctr:
			if el < avg:
				pairs += ctr[el] * ctr[target - el]
			elif el == avg:
				pairs += ctr[el] * (ctr[target - el] - 1) // 2
	print(pairs)


from __future__ import division, print_function
import math
import sys
import os
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')

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 I():
	return int(input())

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
import itertools
from sys import maxsize, stdout, stdin, stderr
mod = int(1000000000.0 + 7)
import sys

def S():
	return list(map(str, input().strip()))

def grid(r, c):
	return [lint() for i in range(r)]
from collections import defaultdict, Counter, deque
import math
import heapq
from heapq import heappop, heappush
import bisect
from math import factorial, inf
from itertools import groupby
from itertools import permutations as comb

def gcd(a, b):
	while b:
		a %= b
		tmp = a
		a = b
		b = tmp
	return a

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

def check_prime(n):
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def nCr(n, r):
	return fact(n) // (fact(r) * fact(n - r))

def fact(n):
	res = 1
	for i in range(2, n + 1):
		res = res * i
	return res

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

def ask(a, b, c):
	print(c, a, b, flush=True)
	n = I()
	return n

def linear_sieve(n):
	is_composite = [False] * n
	prime = []
	for i in range(2, n):
		if not is_composite[i]:
			prime.append(i)
		for j in prime:
			is_composite[i * j] = True
			if i % prime == 0:
				break
	return prime

def dfs(i, p, d):
	(a, tmp) = (0, 0)
	for j in d[i]:
		if j != p:
			a += 1
			tmp += dfs(j, i)
	if a == 0:
		return 0
	return tmp / a + 1

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n // i
	if n > 2:
		l.append(n)
	return l
d = []
primes = []
prim = [0] * (10 ** 5 + 1)

def sieve(n):
	for i in range(n):
		d.append(i)
	for i in range(2, n):
		if d[i] == i:
			prim[i] = 1
			primes.append(i)
		j = 0
		while j < len(primes) and primes[j] <= d[i] and (primes[j] * i < n):
			d[i * primes[j]] = primes[j]
			j += 1

def primeFactors(n):
	factors = []
	while n != 1:
		factors.append(d[n])
		n //= d[n]
	return factors
mod = 1000000007
t = 1
t = I()
for _ in range(t):
	n = I()
	s = lint()
	ans = 0
	k = sum(s) / n
	d = defaultdict(lambda : 0)
	for i in range(n):
		d[s[i]] += 1
	for i in range(n):
		if (2 * k - s[i]) % 1 != 0:
			continue
		tmp = d[int(2 * k - s[i])]
		if tmp > 0:
			if s[i] == k:
				ans += tmp - 1
			else:
				ans += tmp
	print(ans // 2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = 2 * sum(a) / n
	if s != s // 1:
		print(0)
	else:
		count = 0
		c = dict()
		for i in a:
			if i in c:
				c[i] += 1
			else:
				c[i] = 1
		for (i, num) in c.items():
			if i <= s and 2 * i != s:
				sec = s - i
				if sec in c:
					count += num * c[sec]
			elif 2 * i == s:
				count += 2 * (num * (num - 1) // 2)
		print(count // 2)


import sys
inp = sys.stdin.readline

def solve():
	n = int(inp())
	a = list(map(int, inp().split()))
	s2 = sum(a) * 2
	d = {}
	r = 0
	for i in range(n):
		v = s2 - a[i] * n
		r += d.get(v, 0)
		d[a[i] * n] = d.get(a[i] * n, 0) + 1
	print(r)

def main():
	for i in range(int(inp())):
		solve()
main()


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

def split(word):
	return [char for char in word]

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def main():
	for i in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		seto = {}
		k = sum(a)
		seto[a[0]] = 1
		ans = 0
		for j in range(1, n):
			l = n * k - n * a[j] - k * (n - 2)
			if l % n == 0:
				if l // n in seto:
					ans += seto[l // n]
			if a[j] in seto:
				seto[a[j]] += 1
			else:
				seto[a[j]] = 1
		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()


t = int(input())
solution = []
for testCase in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	s = sum(nums)
	if 2 * s % n != 0:
		solution.append(0)
		continue
	desiredSum = 2 * s // n
	numMap = {}
	ans = 0
	for num in nums:
		if desiredSum - num in numMap:
			ans += numMap[desiredSum - num]
		if num in numMap:
			numMap[num] += 1
		else:
			numMap[num] = 1
	solution.append(ans)
for ans in solution:
	print(ans)


for iteration in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sum_a = sum(a)
	k = sum_a / n
	if k * 10 % 5 != 0:
		print(0)
		continue
	pairs = {}
	total = 0
	required = 2 * k
	for element in a:
		total += pairs.get(required - element, 0)
		if element in pairs.keys():
			pairs[element] += 1
		else:
			pairs[element] = 1
	print(total)


from collections import defaultdict

def f(az):
	s = sum(az)
	trgt = 2 * s / n
	if not trgt.is_integer():
		return 0
	res = 0
	ht = defaultdict(int)
	for (i, x) in enumerate(az):
		new_trgt = trgt - x
		if new_trgt in ht:
			res += ht[new_trgt]
		ht[x] += 1
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	az = [int(x) for x in input().split()]
	print(f(az))


import math

def check(nums, numsDict):
	s = sum(nums)
	l = len(nums)
	if s * (l - 2) % l != 0:
		return 0
	else:
		target = s - s * (l - 2) // l
		return twoSum(numsDict, target)

def twoSum(numsDict, target):
	res = 0
	for n in numsDict:
		if target - n in numsDict:
			if n < target - n:
				res += numsDict[n] * numsDict[target - n]
			elif n == target - n:
				res += math.comb(numsDict[n], 2)
	return res

def main():
	numOfTest = int(input())
	res = []
	for _ in range(numOfTest):
		input()
		nums = list(map(int, input().split()))
		numsDict = {}
		for n in nums:
			if n in numsDict:
				numsDict[n] += 1
			else:
				numsDict[n] = 1
		res.append(check(nums, numsDict))
	print(*res, sep='\n')
main()


n = int(input())
from collections import Counter
for i in range(n):
	k = int(input())
	a = list(map(int, input().split()))
	c = Counter(a)
	x = 2 * sum(a) / k
	a = set(a)
	if x % 1 == 0:
		x = int(x)
		ans = 0
		for j in a:
			if j <= x // 2:
				if j != x - j:
					ans += c[j] * c[x - j]
				else:
					ans += (c[j] - 1) * c[x - j] // 2
		print(ans)
		del ans, a, x
	else:
		print(0)


for _ in range(int(input())):
	n = int(input())
	meanx2 = 0
	all_numbers = list()
	for i in input().split():
		i = int(i)
		meanx2 += i
		all_numbers.append(i)
	if 2 * meanx2 % n != 0:
		print(0)
		continue
	meanx2 = 2 * meanx2 // n
	lower = list()
	mid = 0
	upper = dict()
	for i in all_numbers:
		if i < meanx2 / 2:
			lower.append(i)
		elif i > meanx2 / 2:
			old = upper.get(i, 0)
			upper[i] = old + 1
		else:
			mid += 1
	answer = 0
	for i in lower:
		answer += upper.get(meanx2 - i, 0)
	answer += (mid - 1) * mid // 2
	print(answer)


import sys, os, io
input = sys.stdin.readline
PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def bin32(num):
	return '{0:032b}'.format(num)

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]

def ls():
	return [i for i in input().split()]
from collections import defaultdict
for t in range(ii()):
	t += 1
	n = ii()
	a = li()
	g = 2 * sum(a)
	f = defaultdict(lambda : 0)
	for j in range(n):
		a[j] *= n
		f[a[j]] += 1
	ans = 0
	for i in f:
		j = g - i
		if j == i:
			ans += f[i] * (f[i] - 1) // 2
		elif j < i and j in f:
			ans += f[i] * f[j]
	print(ans)


def get_pairs(l, val):
	from collections import Counter
	d = Counter()
	count = 0
	for (i, n) in enumerate(l):
		if val - n in d:
			count += d[val - n]
		d[n] += 1
	return count
for _ in range(int(input())):
	N = int(input())
	l = list(map(int, input().split()))

	def func():
		S = sum(l)
		if 2 * S % N != 0:
			return 0
		return get_pairs(l, 2 * S // N)
	print(func())


for _ in range(int(input())):
	n = int(input())
	d = {}
	l = list(map(int, input().split()))
	s = sum(l) * 2
	ans = 0
	if s % n == 0:
		s = s // n
		for i in range(n):
			temp = s - l[i]
			if temp in d:
				ans += d[temp]
			if l[i] in d:
				d[l[i]] += 1
			else:
				d[l[i]] = 1
	print(ans)


from collections import defaultdict

def main():
	n = int(input())
	l = list(map(int, input().split()))
	mean = 2 * sum(l) / n
	d = defaultdict(int)
	ans = 0
	for x in l:
		if mean - x in d:
			ans += d[mean - x]
		d[x] += 1
	print(ans)
for _ in range(int(input())):
	main()


def getPairsCount(arr, n, sum):
	unordered_map = {}
	count = 0
	for i in range(n):
		if sum - arr[i] in unordered_map:
			count += unordered_map[sum - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return count

def solve(arr, n):
	sm = sum(arr)
	mean = sm / n
	val = round(sm - mean * (n - 2), 3)
	if int(val) != val:
		return 0
	return getPairsCount(arr, n, int(val))
for i in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	print(solve(arr, n))


t = int(input())
numbers = []
for i in range(t):
	a = int(input())
	numbers.append(list(map(float, input().split())))

def mean(a):
	return sum(a) / len(a)

def c_pairs(a):
	k = mean(a)
	n = len(a)
	count = 0
	d = {}
	for (i, cur) in enumerate(a):
		if cur not in d:
			d[cur] = []
		hist = 2 * k - cur
		if hist in d:
			count += len(d[hist])
		d[cur].append(i)
	return count
for i in range(t):
	print(c_pairs(numbers[i]))


from collections import Counter as co

def f():
	n = int(input())
	l = list(map(int, input().split()))
	s = sum(l)
	if 2 * s % n:
		return 0
	d = co(l)
	c = 0
	x = 2 * s // n
	for i in d:
		if x - i in d:
			if i != x - i:
				c += d[i] * d[x - i]
			else:
				c += d[i] * (d[i] - 1)
	return c // 2
for _ in range(int(input())):
	print(f())


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	som = sum(l)
	ans = 0
	d = {}
	for i in l:
		x = 2 * som - n * i
		if x in d:
			ans += d[x]
		g = n * i
		if g in d:
			d[g] += 1
		else:
			d[g] = 1
	sys.stdout.write(str(ans) + '\n')


tc = int(input())
for i in range(tc):
	n = int(input())
	arr = list(map(int, input().split()))
	hm = {}
	for i in range(n):
		if arr[i] in hm:
			hm[arr[i]] += 1
		else:
			hm[arr[i]] = 1
	s = sum(arr)
	mean = s / n
	ans = 0
	req = s - mean * (n - 2)
	for i in range(n):
		if req - arr[i] in hm:
			if arr[i] == req - arr[i]:
				ans += hm[req - arr[i]]
				ans -= 1
			else:
				ans += hm[req - arr[i]]
			hm[arr[i]] -= 1
	print(ans)


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
a = []
(n, k) = (0, 0)
b = []
vis = []
tot = 0
time = []
time1 = []
adj = []
mx = -1
eps = 1e-07
x = 0
pref = []
lvl = []

def update_it(bit, i, val):
	n = len(bit)
	while i < n:
		bit[i] += val
		i += i & -i

def get_ans(bit, i):
	n = len(bit)
	tot = 0
	while i > 0:
		tot += bit[i]
		i -= i & -i
	return tot

def hnbhai(tc):
	n = sb()
	a = sd()
	s = 0
	for i in a:
		s += i
	temp = s * (n - 2) / n
	t = a.copy()
	t.sort()
	if int(temp) != temp:
		print(0)
		return
	temp = s - temp
	dic = dict()
	ans = 0
	for i in t:
		tt = temp - i
		ans += dic.get(tt, 0)
		dic[i] = dic.get(i, 0)
		dic[i] += 1
	print(ans)
for _ in range(sb()):
	hnbhai(_ + 1)


from collections import defaultdict, Counter
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	s = sum(a)
	if 2 * s % n != 0:
		print(0)
	else:
		an = 0
		x = 2 * s // n
		z = Counter(a)
		if x % 2 == 0:
			an += z[x // 2] * (z[x // 2] - 1)
		for i in a:
			if x - i != i:
				if z[x - i]:
					an += z[x - i]
		print(an // 2)


import math
from collections import defaultdict, Counter
from bisect import bisect_left
from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = defaultdict(int)
	s = sum(a)
	if s * 2 % n != 0:
		print(0)
	else:
		target = s * 2 // n
		ans = 0
		for x in a:
			if x in b:
				ans += b[x]
			b[target - x] += 1
		print(ans)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
from itertools import permutations
from operator import itemgetter
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')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	if 2 * s % n:
		print(0)
		continue
	x = 2 * s // n
	d = dict()
	for i in a:
		d[i] = d.get(i, 0) + 1
	ans = 0
	tot = 0
	for i in d:
		z = x - i
		if z in d:
			if i != z:
				ans += d[i] * d[z]
			else:
				tot += d[i] * (d[i] - 1) // 2
	ans //= 2
	ans += tot
	print(ans)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10

def solve(N, A):
	S = sum(A)
	if 2 * S % N != 0:
		return 0
	ans = 0
	counter = collections.Counter(A)
	for (a, n) in counter.items():
		b = 2 * S // N - a
		if a < b:
			if b in counter:
				ans += n * counter[b]
		elif a == b:
			ans += n * (n - 1) // 2
	return ans
T0 = int(input())
for _ in range(T0):
	N = int(input())
	A = list(map(int, input().split()))
	print(solve(N, A))


from sys import stdin, stdout
from collections import defaultdict
import bisect
import math
input = stdin.readline

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

def f(arr, n, s):
	unordered_map = {}
	cnt = 0
	for i in range(n):
		if s - arr[i] in unordered_map:
			cnt += unordered_map[s - arr[i]]
		if arr[i] in unordered_map:
			unordered_map[arr[i]] += 1
		else:
			unordered_map[arr[i]] = 1
	return cnt
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(inp())
	s = sum(a)
	m = s / n * (n - 2)
	m = s - m
	if m % 1 == 0:
		print(f(a, n, int(m)))
	else:
		print(0)


from collections import Counter

def solve():
	n = int(input())
	arr = list(map(int, input().split()))
	su = sum(arr)
	if 2 * su % n:
		return 0
	k = 2 * su // n
	cnt = Counter(arr)
	ans = 0
	for a in arr:
		ans += cnt[k - a]
		if 2 * a == k:
			ans -= 1
	return ans // 2
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	print(solve())


T = int(input())
for _ in range(T):
	N = int(input())
	L = list(map(int, input().split()))
	L.sort()
	S = sum(L)
	if 2 * S % N != 0:
		print(0)
	else:
		L2 = []
		last = L[0]
		nb = 0
		for elt in L:
			if elt == last:
				nb += 1
			else:
				L2.append((last, nb))
				last = elt
				nb = 1
		L2.append((last, nb))
		O = 2 * S // N
		P1 = 0
		P2 = len(L2) - 1
		ans = 0
		while P1 <= P2:
			M = L2[P1][0] + L2[P2][0]
			if M > O:
				P2 -= 1
			elif M == O:
				if P1 == P2:
					ans += L2[P1][1] * (L2[P1][1] - 1) // 2
				else:
					ans += L2[P1][1] * L2[P2][1]
				P1 += 1
				P2 -= 1
			else:
				P1 += 1
		print(ans)


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	agg = 0
	dct = {}
	for i in arr:
		dct[i] = dct.get(i, 0) + 1
		agg += i
	temp = n
	if n % 2 == 0:
		temp //= 2
	if agg % temp != 0:
		print(0)
		continue
	total = agg * 2 // n
	ans = 0
	for (k, v) in dct.items():
		if total == k * 2:
			ans += v * (v - 1)
		else:
			ans += v * dct.get(total - k, 0)
	print(ans // 2)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	summ = sum(a)
	if 2 * summ % n != 0:
		print(0)
	else:
		target = 2 * summ // n
		count = 0
		a.sort()
		hash1 = {}
		for i in a:
			if target - i in hash1:
				count += hash1[target - i]
			if i in hash1:
				hash1[i] += 1
			else:
				hash1[i] = 1
		print(count)


T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	MEAN = sum(A) / N
	REMOVABLE = MEAN * 2
	(i, j) = (0, N - 1)
	count = 0
	unordered_map = {}
	for i in range(N):
		if REMOVABLE - A[i] in unordered_map:
			count += unordered_map[REMOVABLE - A[i]]
		if A[i] in unordered_map:
			unordered_map[A[i]] += 1
		else:
			unordered_map[A[i]] = 1
	print(count)


import sys
import collections
input = sys.stdin.readline

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	cnt = collections.Counter(a)
	avg = sum(a) / n
	ans = 0
	for x in cnt:
		y = avg * 2 - x
		if x == y:
			ans += (cnt[x] - 1) * cnt[x] // 2
		elif x < y:
			ans += cnt[x] * cnt[y]
	print(ans)
for _ in range(int(input())):
	solve()


from collections import Counter, deque
import math
from random import randint
from bisect import bisect
import sys
import re
MOD = 1000000007
MAX = sys.maxsize
MIN = -sys.maxsize

class get:

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

	def str():
		return input().split()

	def float():
		return list(map(float, input().split()))

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

def sqrt(x):
	return int(math.sqrt(x)) + 1

def gcd(*args):
	result = args[0]
	for item in args:
		result = math.gcd(result, item)
	return result

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

def solve():
	n = int(input())
	a = get.int()
	sum_ = sum(a)
	mean = sum(a) / n
	a.sort()
	d = Counter(a)
	res = 0
	for i in range(n):
		if a[i] == 2 * mean - a[i]:
			res += d[a[i]] - 1
		else:
			res += d[2 * mean - a[i]]
	print(res // 2)
for _ in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	s = sum(A)
	target_sum = 2 * s / n
	if 2 * s % n != 0:
		print(0)
	else:
		A_map = dict.fromkeys(A, 0)
		for i in A:
			A_map[i] += 1
		ans = 0
		for i in A:
			req = target_sum - i
			if req in A_map:
				ans += A_map[req]
			if i == req:
				ans -= 1
		print(int(ans // 2))


from math import floor
from collections import defaultdict

def delete_two(array):
	cnt = 0
	if 2 * sum(array) % len(array) != 0:
		return 0
	val = 2 * sum(array) // len(array)
	mp = defaultdict(int)
	for x in array:
		if val - x in mp:
			cnt += mp[val - x]
		mp[x] += 1
	return cnt

def main():
	t = int(input())
	for i in range(t):
		_ = input()
		array = list(map(int, input().split()))
		print(delete_two(array))
main()


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	k = 2 * sum(a) / n
	(l, r) = (0, n - 1)
	ans = set()
	while l != r:
		if a[l] + a[r] == k:
			ans.add((a[l], a[r]))
			l += 1
		elif a[l] + a[r] < k:
			l += 1
		else:
			r -= 1
	b = 0
	d = {}
	for e in ans:
		d[e[0]] = 0
		d[e[1]] = 0
	for i in range(n):
		if a[i] in d:
			d[a[i]] += 1
	for e in ans:
		if e[0] == e[1]:
			i = d[e[0]]
			b += i * (i - 1) // 2
		else:
			i = d[e[0]]
			j = d[e[1]]
			b += i * j
	print(b)


t = int(input())
for case in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = sum(a)
	avg = s / n
	k = s - avg * (n - 2)
	d = {}
	count = 0
	for i in range(n):
		if k - a[i] in d:
			count += d[k - a[i]]
		if a[i] in d:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	print(count)


n = int(input())
for k in range(n):
	count = int(input())
	sums = 0
	arrs = {}
	arr = list(map(int, input().split(' ')))
	for j in arr:
		sums += j
		if j in arrs:
			arrs[j] += 1
		else:
			arrs[j] = 1
	result = 0
	mid = sums / count
	need = sums * 2 / count
	for j in arr:
		a2 = need - j
		if a2 not in arrs:
			continue
		if arrs[a2] == 0:
			continue
		if a2 in arrs:
			result += arrs[a2]
		arrs[j] -= 1
		if a2 == j:
			result -= 1
	print(result)


import sys
import os.path
from collections import *
import math
import bisect
import heapq as hq
from fractions import Fraction
from random import randint
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline

def solve():
	n = int(input())
	arr = [int(x) for x in input().split()]
	res = 0
	k = 2 * sum(arr) / n
	h = Counter()
	for i in range(n):
		res += h[k - arr[i]]
		h[arr[i]] += 1
	print(res)
t = int(input())
while t:
	t -= 1
	solve()


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	k = sum(a) / n
	counts = dict()
	for i in a:
		counts[i] = counts.get(i, 0) + 1
	numbers = sorted(counts.keys())
	(point1, point2) = (0, len(numbers) - 1)
	ans = 0
	while point2 >= point1:
		num1 = numbers[point1]
		num2 = numbers[point2]
		if num1 + num2 > 2 * k:
			point2 -= 1
		elif num1 + num2 < 2 * k:
			point1 += 1
		else:
			if num1 != num2:
				ans += counts[num1] * counts[num2]
			else:
				ans += (counts[num1] ** 2 - counts[num1]) // 2
			point2 -= 1
			point1 += 1
	print(str(ans) + '\n')


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 collections import Counter, defaultdict
import math
import heapq
import bisect

def nck(n, k):
	res = 1
	for i in range(1, k + 1):
		res = res * (n - i + 1) // i
	return res
m = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	d = {}
	a = 0
	d[0] = 0
	k = sum(arr) / n
	for i in range(n):
		a += d.get(2 * k - arr[i], 0)
		d[arr[i]] = d.get(arr[i], 0) + 1
	print(a)


from collections import Counter
mxn = 10 ** 10
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	sm = sum(arr)
	if 2 * sm % n != 0:
		print(0)
		continue
	res = 0
	target = 2 * sm // n
	dct = Counter(arr)
	for num in set(arr):
		if target - num == num:
			res += dct[num] * (dct[num] - 1)
		else:
			res += dct[num] * dct[target - num]
	print(res // 2)


from collections import defaultdict
import sys
input = sys.stdin.readline

def inp():
	return int(input())

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

def input_string():
	s = input()
	return s[:-1]

def input_string_l():
	s = input()
	return list(s[:len(s) - 1])

def input_int_gen():
	return map(int, input().split())
tests = inp()
for _ in range(tests):
	n = inp()
	a = input_list()
	sumi = sum(a)
	target = sumi * 2 / n
	if sumi * 2 % n != 0:
		print(0)
		continue
	c = defaultdict(int)
	for i in a:
		c[target - i] += 1
	ret = 0
	k = 0
	for i in a:
		if i == target - i:
			c[i] -= 1
			ret += c[i]
		elif i < target - i:
			ret += c[i]
	print(ret)


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	A = 2 * sum(s) / n
	a = {}
	ans = 0
	for i in s:
		if A - i in a:
			ans += a[A - i]
		if i not in a:
			a[i] = 0
		a[i] += 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import math
from collections import Counter

def func(n, array):
	sum_all = sum(array)
	if sum_all * 2 % n != 0:
		return 0
	target = sum_all * 2 // n
	counter = Counter(array)
	count = 0
	keys = sorted(counter.keys())
	for key in keys:
		if key * 2 > target:
			break
		elif key * 2 == target:
			count += counter[key] * (counter[key] - 1) // 2
		elif target - key in counter:
			count += counter[key] * counter[target - key]
	return count

def main():
	num_test = int(parse_input())
	result = []
	for _ in range(num_test):
		n = int(parse_input())
		array = [int(i) for i in parse_input().split()]
		result.append(func(n, array))
	print('\n'.join(map(str, result)))
parse_input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for t in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	numbers = {}
	ans = 0
	sum_ = 2 * sum(a)
	if sum_ % n != 0:
		print(0)
		continue
	tk = sum_ // n
	for num in a:
		if tk - num in numbers:
			ans += numbers[tk - num]
		if num not in numbers:
			numbers[num] = 0
		numbers[num] += 1
	print(ans)