// dist/FinalCode/Algo/binarySearch.js
var binSearch = function(arrayData, data, customLowIdx, customHighIdx) {
  var low = customLowIdx;
  var high = customHighIdx;
  var mid;
  while (high - low > 10) {
    mid = Math.floor((high - low) / 2 + low);
    if (data <= arrayData[mid]) {
      high = mid;
    } else {
      low = mid;
    }
  }
  for (var idx = low; idx <= high; idx++) {
    if (arrayData[idx] === data) {
      return idx;
    }
  }
  return -1;
};

// dist/FinalCode/Common/InputOutputClass.js
var Input = function() {
  function Input2(inputData) {
    var _this = this;
    this.SettleStream = function() {
      var re = /\s+/;
      _this.inputWords = _this.inputStream.split(re);
      _this.inputWordsLength = _this.inputWords.length;
    };
    this.getLength = function() {
      return _this.inputWordsLength;
    };
    this.getEveryWord = function() {
      return _this.inputWords;
    };
    this.getNextWord = function() {
      _this.inputWordsCount++;
      if (_this.inputWordsLength < _this.inputWordsCount) {
        return "";
      }
      return _this.inputWords[_this.inputWordsCount - 1];
    };
    this.getNextString = function() {
      return _this.getNextWord();
    };
    this.getNextBigInt = function() {
      return BigInt(_this.getNextWord());
    };
    this.getNextNumber = function() {
      return Number(_this.getNextWord());
    };
    this.getNextInt = function() {
      return parseInt(_this.getNextWord(), 10);
    };
    this.getNextFloat = function() {
      return parseFloat(_this.getNextWord());
    };
    this.inputWordsCount = 0;
    this.inputStream = inputData;
  }
  Input2.prototype.SetStream = function(chunk) {
    this.inputStream += chunk;
  };
  Input2.prototype.getNextIntArray = function(elementCount) {
    var resultArray = new Array(elementCount);
    for (var idx = 0; idx < elementCount; idx++) {
      resultArray[idx] = this.getNextInt();
    }
    return resultArray;
  };
  return Input2;
}();
var InputOutputClass_default = Input;
var writeLine = function(outputElement) {
  var _internalWrite = function(_internalOutputElement) {
    process.stdout.write(_internalOutputElement);
  };
  _internalWrite(String(outputElement) + "\n");
};

// dist/main.js
var rw = new InputOutputClass_default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.SetStream(chunk);
});
process.stdin.on("end", function() {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = function() {
  testCases();
};
var testCases = function() {
  var test = rw.getNextInt();
  for (var i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = function() {
  var n = rw.getNextInt();
  var nums = rw.getNextIntArray(n);
  var sum = 0;
  for (var i = 0; i < n; i++) {
    sum += nums[i];
  }
  var avg = sum / n;
  nums.sort(function(a, b2) {
    return a - b2;
  });
  var answer = 0;
  var j = n - 1;
  for (var i = 0; i < n - 1; i++) {
    while (nums[i] + nums[j] > 2 * avg && i < j) {
      j--;
    }
    if (!(i < j)) {
      break;
    }
    if (nums[i] + nums[j] === 2 * avg) {
      var b = binSearch(nums, nums[j], i + 1, n - 1);
      if (b !== -1) {
        answer += j - b + 1;
      }
    }
  }
  writeLine("" + answer);
};

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = BigInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => BigInt(cur));
    let sum = 0n;
    for (let i = 0; i < n; i++) sum += arr[i];
    let t = sum * (n - 2n);
    if (t % n) console.log(0);
    else {
      t = t / n;
      let p = sum - t;
      let obj = {};
      for (let i = 0; i < n; i++) {
        if (!obj[arr[i]]) obj[arr[i]] = 1n;
        else obj[arr[i]]++;
      }
      let cnt = 0n;
      if (n - 2n === 1n) {
        if (obj[t]) console.log(obj[t] + "");
        else console.log(0);
        continue;
      }
      for (let i = 0; i < n; i++) {
        obj[arr[i]]--;
        let k = p - arr[i];
        if (obj[k]) cnt += obj[k];
      }
      console.log(cnt + "");
    }
  }
};
solve();

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let ls = [];

function solve(){
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let u = 0; u < t; u++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(i => parseInt(i));
        const cnt = {};
        let sum = 0;
        for (let i = 0; i < n; i++){
            if (cnt[a[i]]){
                cnt[a[i]]++;
            }
            else{
                cnt[a[i]] = 1;
            }
            sum += a[i];
        }

        const pairSum = 2*sum/n;
        if (!Number.isInteger(pairSum)){
            console.log('0');
            continue;
        }

        let ans = 0;
        for (let i = 0; i < n; i++){
            let b = pairSum - a[i];
            let c = 0;
            if (cnt[b]){
                c = cnt[b];
            }
            if (a[i] == b){
                c = Math.max(0, c - 1);
            }
            ans += c;
        }
        console.log(ans/2);
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}
const rla = () => readLine().split(' ').map(x => Number(x));

function main () {
	let t = rl();
	while (t--) {
		let n = rl();
		let a = rla();

		a.sort((x, y) => x - y);
		let sum = 0;
		for (x of a) sum += x;
		let m = sum / n;

		let i = 0; j = n - 1, ans = 0;;
		while (i < j) {
			if (a[i] + a[j] == 2 * m) {
				if (a[i] == a[j]) {
					elms = j - i + 1;
					ans += elms * (elms - 1) / 2;
					break;
				}
				let i0 = i, j0 = j;
				i++;
				while (a[i] == a[i-1]) i++;
				j--;
				while (a[j] == a[j+1]) j--;
				ans += (i - i0) * (j0 - j);
			}
			else if (a[i] + a[j] < 2 * m) i++;
			else j--;
			//console.log(i,j, a[i] + a[j] , 2 * m);
		}
		console.log(ans);
	}
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = getCountMap(list);
		var sum = 0;
		for(var i = 0; i < N; i++){
			sum += list[i];
		}
		var avg = sum / N;
		var output = 0;
		var ato = 0;
		var keys = Object.keys(map);
		for(var i = 0; i < keys.length; i++){
			var V = map[keys[i]];
			var L = (avg * 2) - keys[i];
			if(L == keys[i]){
				ato = V * (V - 1) / 2;
			}else if(map[L] != null){
				output += map[keys[i]] * map[L];
			}
		}
		myout(output / 2 + ato);
	}
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sum = arr.reduce((s, x) => s + x, 0)
    const target = sum * 2 / n
    // console.log(sum, n, target)
    arr.sort((a, b) => a - b)

    let ans = 0
    for (let i = 0; i < arr.length; i++) {
        const a1 = binarySearch(i + 1, n - 1, x => arr[x] < target - arr[i])
        const a2 = binarySearch(i + 1, n - 1, x => arr[x] <= target - arr[i])
    // console.log(a1, a2)
        ans += a2 - a1
    }
    // console.log('-')
    return ans
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                    map[other] = 0;
                }
                else {
                    map[other] = 0;
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
            }
        }
    }
    return ans;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var sum = 0;
    var mp = {};
    for (var i = 0; i < n; i++) {
      sum += inp[i];
      if (mp.hasOwnProperty(inp[i])) {
        mp[inp[i]]++;
      } else {
        mp[inp[i]] = 1;
      }
    }
    var ans = 0;
    var need = (2 * sum) / n;
    if ((2 * sum) % n !== 0) {
      return 0;
    }
    for (var i = 0; i < n; i++) {
      var req = need - inp[i];
      var val = mp[req] || 0;
      ans += val;
      if (inp[i] == req) ans -= 1;
    }
    return ans / 2;
  }

  while (t--) {
    print(solve());
  }

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = 0;
    for (let i = 0; i < n; i++) sum += arr[i];
    let t = (sum * (n - 2)) / n;
    if (t % 1 !== 0) console.log(0);
    else {
      let p = sum - t;
      let obj = {};
      for (let i = 0; i < n; i++) {
        if (!obj[arr[i]]) obj[arr[i]] = 1;
        else obj[arr[i]]++;
      }
      let cnt = 0;
      if (n - 2 === 1) {
        if (obj[t]) console.log(obj[t]);
        else console.log(0);
        continue;
      }
      for (let i = 0; i < n; i++) {
        obj[arr[i]]--;
        let k = p - arr[i];
        if (obj[k]) cnt += obj[k];
      }
      console.log(cnt);
    }
  }
};
solve();

// dist/FinalCode/Algo/binarySearch.js
var binSearch = function(arrayData, data, customLowIdx, customHighIdx) {
  var low = customLowIdx;
  var high = customHighIdx;
  var mid;
  while (high - low > 10) {
    mid = Math.floor((high - low) / 2 + low);
    if (data <= arrayData[mid]) {
      high = mid;
    } else {
      low = mid;
    }
  }
  for (var idx = low; idx <= high; idx++) {
    if (arrayData[idx] === data) {
      return idx;
    }
  }
  return -1;
};

// dist/FinalCode/Common/InputOutputClass.js
var Input = function() {
  function Input2(inputData) {
    var _this = this;
    this.SettleStream = function() {
      var re = /\s+/;
      _this.inputWords = _this.inputStream.split(re);
      _this.inputWordsLength = _this.inputWords.length;
    };
    this.getLength = function() {
      return _this.inputWordsLength;
    };
    this.getEveryWord = function() {
      return _this.inputWords;
    };
    this.getNextWord = function() {
      _this.inputWordsCount++;
      if (_this.inputWordsLength < _this.inputWordsCount) {
        return "";
      }
      return _this.inputWords[_this.inputWordsCount - 1];
    };
    this.getNextString = function() {
      return _this.getNextWord();
    };
    this.getNextBigInt = function() {
      return BigInt(_this.getNextWord());
    };
    this.getNextNumber = function() {
      return Number(_this.getNextWord());
    };
    this.getNextInt = function() {
      return parseInt(_this.getNextWord(), 10);
    };
    this.getNextFloat = function() {
      return parseFloat(_this.getNextWord());
    };
    this.inputWordsCount = 0;
    this.inputStream = inputData;
  }
  Input2.prototype.SetStream = function(chunk) {
    this.inputStream += chunk;
  };
  Input2.prototype.getNextIntArray = function(elementCount) {
    var resultArray = new Array(elementCount);
    for (var idx = 0; idx < elementCount; idx++) {
      resultArray[idx] = this.getNextInt();
    }
    return resultArray;
  };
  return Input2;
}();
var InputOutputClass_default = Input;
var writeLine = function(outputElement) {
  var _internalWrite = function(_internalOutputElement) {
    process.stdout.write(_internalOutputElement);
  };
  _internalWrite(String(outputElement) + "\n");
};

// dist/main.js
var rw = new InputOutputClass_default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.SetStream(chunk);
});
process.stdin.on("end", function() {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = function() {
  testCases();
};
var testCases = function() {
  var test = rw.getNextInt();
  for (var i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = function() {
  var n = rw.getNextInt();
  var nums = rw.getNextIntArray(n);
  var sum = 0;
  for (var i = 0; i < n; i++) {
    sum += nums[i];
  }
  var avg = sum / n;
  nums.sort(function(a, b2) {
    return a - b2;
  });
  var answer = 0;
  var j = n - 1;
  for (var i = 0; i < n - 1; i++) {
    while (nums[i] + nums[j] !== 2 * avg && i < j) {
      j--;
    }
    if (!(i < j)) {
      break;
    }
    var b = binSearch(nums, nums[j], i + 1, n - 1);
    answer += j - b + 1;
  }
  writeLine(answer);
};

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                }
                else {
                    delete map[other]
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
                delete map[other];
                delete map[inp[i]];
            }
        }
    }
    return ans;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = 2 * (tot / n);
    var map = {};
    for(var i1 = 0;i1 < n;i1++) {
        if(map[inp[i1]]) {
            map[inp[i1]] += 1;
        }
        else {
            map[inp[i1]] = 1;
        }
    }
    var ans = 0;
    for(var i = 0;i < n;i++) {
        var other = rem - inp[i];
        if(map[other]) {
            var f1 = map[other];
            var f2 = map[inp[i]];

            if(other == inp[i]) {
                if(f1 > 1) {
                    ans += (f1 * (f1 - 1)) / 2;
                }
                else {
                    map[other] = 0;
                }
            }
            else {
                ans += (f1 * f2);
                map[inp[i]] = 0;
                map[other] = 0;
            }
        }
    }
    return ans;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    var i = 0, j = n - 1;
    var ans = 0;
    while(i < j) {
        if(inp[i] + inp[j] > rem) {
            j -= 1;
        }
        else if(inp[i] + inp[j] < rem) {
            i += 1;
        }
        else {
            var cnti = 1;
            var cntj = 1;
            i = i + 1;
            j = j - 1;
            while(i < j && inp[i] == inp[i - 1]) {
                i += 1;
                cnti += 1;
            }
            while(i < j && inp[j] == inp[j + 1]) {
                j -= 1;
                cntj += 1;
            }
            ans += (cnti * cntj);
        }
    }
    return ans;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    // var i = 0, j = 0;
    // var ans = 0;
    // while(i < j) {
    //     if(inp[i] + inp[j] > rem) {
    //         j -= 1;
    //     }
    //     else if(inp[i] + inp[j] < rem) {
    //         i += 1;
    //     }
    //     else {
    //         var cnti = 1;
    //         var cntj = 1;
    //         var i1 = i + 1;
    //         var j1 = j - 1;
    //         while(i1 < j && inp[i1] == inp[i1 - 1]) {
    //             cnti += 1;
    //         }
    //         while(i < j1 && inp[j1] == inp[j1 + 1]) {
    //             cntj += 1;
    //         }
    //         ans += (cnti * cntj);
    //     }
    // }
    return rem;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var tot = inp.reduce((p, c) => {
        p += c;
        return p;
    }, 0);
    var rem = (tot - ((tot / n) * (n - 2)));
    inp.sort((a, b) => a - b);
    var i = 0, j = 0;
    var ans = 0;
    while(i < j) {
        if(inp[i] + inp[j] > rem) {
            j -= 1;
        }
        else if(inp[i] + inp[j] < rem) {
            i += 1;
        }
        else {
            var cnti = 1;
            var cntj = 1;
            var i1 = i + 1;
            var j1 = j - 1;
            while(i1 < j && inp[i1] == inp[i1 - 1]) {
                cnti += 1;
            }
            while(i < j1 && inp[j1] == inp[j1 + 1]) {
                cntj += 1;
            }
            ans += (cnti * cntj);
        }
    }
    return ans;
  }

  while (t--) {
    print(solve());
  }

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var sum = 0;
    var mp = {};
    for (var i = 0; i < n; i++) {
      sum += inp[i];
      if (mp.hasOwnProperty(inp[i])) {
        mp[inp[i]]++;
      } else {
        mp[inp[i]] = 1;
      }
    }
    var ans = 0;
    var need = (2 * sum) / n;
    if ((2 * sum) % n != 0) {
      return 0;
    }
    for (var i = 0; i < n; i++) {
      var req = need - inp[i];
      ans += mp[req];
      if (inp[i] == req) ans -= 1;
    }
    return ans / 2;
  }

  while (t--) {
    print(solve());
  }


'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  const s = sum(nums);
  const l = nums.length;

  if (s % l !== 0) {
    return -1;
  }

  nums = [Number.NEGATIVE_INFINITY, ...nums];
  const target = s / l;
  const actions = [];

  const go = (i, j, x) => {
    if (!x) {
      return;
    }

    actions.push([i, j, x]);
    nums[i] -= i * x;
    nums[j] += i * x;
  }; // Move everything to the first element

  for (let i = 2; i < nums.length; i++) {
    const element = nums[i];
    const rem = element % i;

    if (rem) {
      go(1, i, i - rem);
    }

    const x = Math.ceil(element / i);
    go(i, 1, x);
  } // Fill everything to the target value

  for (let i = 2; i < nums.length; i++) {
    go(1, i, target);
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

// let p = [2, 3, 5];
// for (let i = 6; i < 1e5; i += 6) {
//   let j, x = i + 1;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
//   x = i + 5;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $(), a = $(n), c = 0, op = [], x, clId = 2, tb = a.sum() / n | 0;
    a.unshift(0);

    let clear = () => {
      For(clId, n, 1, i => {
        clId = i;
        if (a[i] == 0) return;
        if (a[1] >= i - a[i] % i) {
          x = i - a[i] % i;
          if (x > 0) {
            op[c++] = `${1} ${i} ${x}`;
            a[1] -= x;
            a[i] += x;
          }
          x = a[i] / i;
          op[c++] = `${i} ${1} ${x}`;
          a[1] += x * i;
          a[i] -= x * i;
        } else return -1;
      })
    }

    For(2, n, 1, i => {
      if (a[i] == 0) return;
      if (a[i] % i == 0) {
        x = a[i] / i;
        op[c++] = `${i} ${1} ${x}`;
        a[1] += x * i;
        a[i] -= x * i;
      } else if (a[0] >= i - a[i] % i) {
        x = i - a[i] % i
        op[c++] = `${1} ${i} ${x}`;
        a[1] -= x;
        a[i] += x;
        x = a[i] / i;
        op[c++] = `${i} ${1} ${x}`;
        a[1] += x * i;
        a[i] -= x * i;
      } else if (a[i] > i) {
        x = a[i] / i | 0;
        op[c++] = `${i} ${1} ${x}`;
        a[1] += x * i;
        a[i] -= x * i;
      }
      clear();
    })

    // log(a, op)

    For(2, n, 1, i => {
      if (a[i] >= tb) return;
      if (a[1] < tb - a[i]) return;
      x = tb - a[i];
      op[c++] = `${1} ${i} ${x}`;
      a[1] -= x;
      a[i] += x;
    })

    // log(a, op)
    a.shift();
    if (a.some(v => v != tb)) out.push(-1);
    else {
      out.push(c);
      out.push(...op);
    }
  }
  log(out.join('\n'))
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

// let p = [2, 3, 5];
// for (let i = 6; i < 1e5; i += 6) {
//   let j, x = i + 1;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
//   x = i + 5;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $()
    let a = $(n)
    let s = a.sum()
    if (s % n != 0) {
      out.push(-1);
      continue;
    }
    let tb = s / n;
    let c = 0;
    let op = [];
    for (let i = 1; i < n; i++) {
      let x = a[i] / (i + 1) | 0;
      if (x == 0) continue;
      op[c++] = `${i + 1} ${1} ${x}`;
      a[0] += (i + 1) * x;
      a[i] -= (i + 1) * x;
    }
    // log(1, a, op);
    kothe = false;
    for (let i = n - 1; i >= 1; i--) {
      if (a[i] > tb) {
        let x = (i + 1) - (a[i] - tb) % (i + 1);
        op[c++] = `${1} ${i + 1} ${x}`;
        a[0] -= x;
        a[i] += x;
        if (a[0] < 0) {
          kothe = true;
          break;
        }
        x = (a[i] - tb) / (i + 1);
        op[c++] = `${i + 1} ${1} ${x}`;
        a[0] += x * (i + 1);
        a[i] -= x * (i + 1);
      }
    }
    if (kothe) {
      out.push(-1);
      continue;
    }
    // log(2, a, op);
    for (let i = 1; i < n; i++) {
      if (a[i] < tb) {
        let x = tb - a[i];
        op[c++] = `${1} ${i + 1} ${x}`;
        a[0] -= x;
        a[i] += x;
      }
    }
    // log(3, a, op);
    out.push(c);
    out.push(...op);
  }
  log(out.join('\n'));
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

// let p = [2, 3, 5];
// for (let i = 6; i < 1e5; i += 6) {
//   let j, x = i + 1;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
//   x = i + 5;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $()
    let a = $(n)
    let s = a.sum()
    if (s % n != 0) {
      out.push(-1);
      continue;
    }
    let tb = s / n;
    let c = 0;
    let op = [];
    for (let i = 1; i < n; i++) {
      let x = a[i] / (i + 1) | 0;
      if (x == 0) continue;
      op[c++] = `${i + 1} ${1} ${x}`;
      a[0] += (i + 1) * x;
      a[i] -= (i + 1) * x;
    }
    // log(1, a, op);
    for (let i = n - 1; i >= 1; i--) {
      if (a[i] > tb) {
        let x = (i + 1) - (a[i] - tb) % (i + 1);
        op[c++] = `${1} ${i + 1} ${x}`;
        a[0] -= x;
        a[i] += x;
        x = (a[i] - tb) / (i + 1);
        op[c++] = `${i + 1} ${1} ${x}`;
        a[0] += x * (i + 1);
        a[i] -= x * (i + 1);
      }
    }
    // log(2, a, op);
    for (let i = 1; i < n; i++) {
      if (a[i] < tb) {
        let x = tb - a[i];
        op[c++] = `${1} ${i + 1} ${x}`;
        a[0] -= x;
        a[i] += x;
      }
    }
    // log(3, a, op);
    out.push(c);
    out.push(...op);
  }
  log(out.join('\n'));
}

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  // 1 1 1 2 0
  const s = sum(nums);

  if (s % nums.length !== 0) {
    return -1;
  }

  const target = s / nums.length;
  const actions = [];

  for (let i = nums.length - 1; i >= 0; i--) {
    let element = nums[i];

    while (element !== target) {
      if (element > target && element > i) {
        const diff = element - target;
        let x = Math.ceil(diff / (i + 1));
        let movement = x * (i + 1);

        if (nums[i] - movement < 0) {
          x--;
          movement -= i + 1;
        }

        actions.push([i + 1, 1, x]);
        nums[0] += movement;
        nums[i] -= movement;

        if (nums[i] < 0) {
          throw new Error('1');
        }
      } else {
        let iIndex = -2,
            iValue = 0;

        for (let j = i - 1; j >= 0; j--) {
          if (nums[j] > iValue && nums[j] >= j + 1) {
            iIndex = j;
            iValue = nums[j];
          }
        }

        if (iIndex < 0) {
          return -2;
        }

        const maxX = Math.floor(iValue / (iIndex + 1));
        const wantedX = Math.ceil((target - element) / (iIndex + 1)) || 1;
        const x = wantedX <= maxX ? wantedX : maxX;
        const movement = x * (iIndex + 1);
        actions.push([iIndex + 1, i + 1, x]);
        nums[i] += movement;
        nums[iIndex] -= movement;

        if (nums[iIndex] < 0) {
          throw new Error('1');
        }
      }

      element = nums[i];
    }
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  // 1 1 1 2 0
  const s = sum(nums);

  if (s % nums.length !== 0) {
    return -1;
  }

  const target = s / nums.length;
  const actions = [];

  for (let i = nums.length - 1; i >= 0; i--) {
    let element = nums[i];

    while (element !== target) {
      if (element > target && element > i) {
        const diff = element - target;
        let x = Math.ceil(diff / (i + 1));
        let movement = x * (i + 1);

        if (nums[i] - movement < 0) {
          x--;
          movement -= i + 1;
        }

        if (x <= 0) {
          throw new Error('4');
        }

        actions.push([i + 1, 1, x]);
        nums[0] += movement;
        nums[i] -= movement;

        if (nums[i] < 0) {
          throw new Error('1');
        }
      } else {
        let iIndex = -2,
            iValue = 0;

        for (let j = i - 1; j >= 0; j--) {
          if (nums[j] > iValue && nums[j] >= j + 1) {
            iIndex = j;
            iValue = nums[j];
          }
        }

        if (iIndex < 0) {
          return -2;
        }

        const maxX = Math.floor(iValue / (iIndex + 1));
        const wantedX = Math.ceil(Math.max(target - element, 1) / (iIndex + 1));
        const x = wantedX <= maxX ? wantedX : maxX;

        if (x <= 0) {
          throw new Error('3');
        }

        const movement = x * (iIndex + 1);
        actions.push([iIndex + 1, i + 1, x]);
        nums[i] += movement;
        nums[iIndex] -= movement;

        if (nums[iIndex] < 0) {
          throw new Error('1');
        }
      }

      element = nums[i];
    }
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  // 1 1 1 2 0
  const s = sum(nums);

  if (s % nums.length !== 0) {
    return -1;
  }

  const target = s / nums.length;
  const actions = [];

  for (let i = nums.length - 1; i >= 0; i--) {
    let element = nums[i];

    while (element !== target) {
      if (element > target && element > i) {
        const diff = element - target;
        let x = Math.ceil(diff / (i + 1));
        let movement = x * (i + 1);

        if (nums[i] - movement < 0) {
          x--;
          movement -= i + 1;
        }

        actions.push([i + 1, 1, x]);
        nums[0] += movement;
        nums[i] -= movement;

        if (nums[i] < 0) {
          throw new Error('1');
        }
      } else {
        let iIndex = -2,
            iValue = 0;

        for (let j = i - 1; j >= 0; j--) {
          if (nums[j] > iValue && nums[j] >= j + 1) {
            iIndex = j;
            iValue = nums[j];
          }
        }

        if (iIndex < 0) {
          return -2;
        }

        const maxX = Math.floor(iValue / (iIndex + 1));
        const wantedX = Math.ceil((target - element) / (iIndex + 1)) || 1;
        const x = wantedX <= maxX ? wantedX : maxX;
        const movement = x * (iIndex + 1);
        actions.push([iIndex + 1, i + 1, x]);
        nums[i] += movement;
        nums[iIndex] -= movement;

        if (nums[iIndex] < 0) {
          throw new Error('1');
        }
      }

      console.log(nums);
      element = nums[i];
    }
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  // 1 1 1 2 0
  const s = sum(nums);

  if (s % nums.length !== 0) {
    return -1;
  }

  const target = s / nums.length;
  const actions = [];

  for (let i = nums.length - 1; i >= 0; i--) {
    let element = nums[i];

    while (element !== target) {
      if (element > target) {
        const diff = element - target;
        const x = Math.ceil(diff / (i + 1));
        const movement = x * (i + 1);
        actions.push([i + 1, 1, x]);
        nums[0] += movement;
        nums[i] -= movement;
      } else {
        let iIndex = -2,
            iValue = 0;

        for (let j = i - 1; j >= 0; j--) {
          if (nums[j] > iValue && nums[j] >= j + 1) {
            iIndex = j;
            iValue = nums[j];
          }
        }

        if (iIndex < 0) {
          return -2;
        }

        const maxX = Math.floor(iValue / (iIndex + 1));
        const wantedX = Math.ceil((target - element) / (iIndex + 1));
        const x = wantedX <= maxX ? wantedX : maxX;
        const movement = x * (iIndex + 1);
        actions.push([iIndex + 1, i + 1, x]);
        nums[i] += movement;
        nums[iIndex] -= movement;
      }

      element = nums[i];
    }
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(nums) {
  // 1 1 1 2 0
  const s = sum(nums);

  if (s % nums.length !== 0) {
    return -1;
  }

  const target = s / nums.length;
  const actions = [];

  for (let i = nums.length - 1; i >= 0; i--) {
    let element = nums[i];

    while (element !== target) {
      if (element > target && element > i) {
        const diff = element - target;
        let x = Math.ceil(diff / (i + 1));
        let movement = x * (i + 1);

        if (nums[i] - movement < 0) {
          x--;
          movement -= i + 1;
        }

        if (x <= 0) {
          throw new Error('4');
        }

        actions.push([i + 1, 1, x]);
        nums[0] += movement;
        nums[i] -= movement;

        if (nums[i] < 0) {
          throw new Error('1');
        }
      } else {
        let iIndex = -2,
            iValue = 0;

        for (let j = i - 1; j >= 0; j--) {
          if (nums[j] > iValue && nums[j] >= j + 1) {
            iIndex = j;
            iValue = nums[j];
          }
        }

        if (iIndex < 0) {
          return -2;
        }

        const maxX = Math.floor(iValue / (iIndex + 1));
        const wantedX = Math.ceil(Math.max(target - element, 1) / (iIndex + 1));
        const x = wantedX <= maxX ? wantedX : maxX;

        if (x <= 0) {
          throw new Error('3');
        }

        const movement = x * (iIndex + 1);
        actions.push([iIndex + 1, i + 1, x]);
        nums[i] += movement;
        nums[iIndex] -= movement;

        if (nums[iIndex] < 0) {
          throw new Error('1');
        }
      }

      element = nums[i];
    }
  }

  if (actions.length > nums.length * 3) {
    return -1;
  }

  return `${actions.length}\n${actions.map(a => a.join(' ')).join('\n')}`;
}

async function main() {
  const input = await tTwoLinesPerStdin();

  for (let t = 0; t < input.length; t++) {
    const [line2] = input[t].slice(1);
    const answer = solve(line2.split(' ').map(Number));
    console.log(answer);
  }
}

main().then();


for (var q = Number (readline ()); q > 0; q--)
    {
    var s = readline ();
    var t = readline ();
    var b = false;

    for (var i = s.length - 1; i >= 0 && !b; i--)
        {
        var z = s.substring (0, i);
        z += (s[i] + z.split ("").reverse ().join (""));

        if (z.indexOf (t) >= 0) { b = true; }
        }

    print (b ? "Yes" : "No");
    }

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let str1 = readline().trim();
    let str2 = readline().trim();
    let obj = {},
      ans = false;
    for (let i = 0; i < str1.length; i++) {
      if (str1[i] === str2[0]) {
        const helper = () => {
          for (let j = 0; j + i < str1.length; j++) {
            let res1 = str1.substring(i, j + i + 1),
              left = j + i + 1;
            if (res1.length < str2.length && left > str2.length - res1.length) {
              for (let st = i + j - 1; res1.length < str2.length; st--)
                res1 += str1[st];
            }
            let ans = true;
            if (res1.length !== str2.length) continue;
            for (let st = 0; st < res1.length; st++) {
              if (str2[st] !== res1[st]) {
                ans = false;
                break;
              }
            }
            if (ans === true) return true;
          }
          return false;
        };
        ans = helper();
        if (ans === true) break;
      }
    }
    if (ans === true) console.log("YES");
    else console.log("NO");
  }
};
solve();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const rev = s => s.split('').reverse().join('');

function main () {
	let t = rn();
	while (t--) {
		let s = rl();
		let t = rl();

		let ans = false;
		for (let i = 0; !ans && i < s.length; i++) {

			tl = t.slice(0, i+1);
			tr = t.slice(i);

			if (tr.indexOf(rev(tl)) == 0 && s.includes(rev(tr)))
				ans = true;
			if (rev(tl).indexOf(tr) == 0 && s.includes(tl))
				ans = true;
		}

		console.log(ans ? 'YES' : 'NO');
	}
}

r=readline
t=+r()
while(t--)
{
    s=r()
    f=r()
    a="";
    ok=false;
    for(i=0;i<s.length;i++){
        a="";
        b="";
        if(s[i]==f[0]){
            a+=s[i];
            p=i;
            l=1;
            left=false;
            while(true){
            pos=l;b=a;po=p;
            while(po-1>=0 && pos<f.length && s[po-1]==f[pos]){ po--; b+=s[po]; pos++;}
            if(b==f)ok=true;

                if(p+1<s.length &&  l<f.length && s[p+1]==f[l] && left==false){
                    p++;
                    a+=s[p];
                    l++;
                }
                 else if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                    p--;
                    a+=s[p];
                    l++;
                    left=true;
                }
                else break;
          }

        }
        if(a==f){
            ok=true;
            break;
        }
    }
    print(ok?"YES":"NO");

}

r=readline
t=+r()
while(t--)
{
    s=r();
    f=r();
    a="";
    ok=false;
    for(i=0;i<s.length;i++){
        a="";
        b="";
        if(s[i]==f[0]){
            a+=s[i];
            p=i;
            l=1;
            left=false;
            while(true){
                        pos=l;
            b=a;
            po=p;
            while(po-1>=0 && pos<f.length && s[po-1]==f[pos]){
                po--;
                b+=s[po];
                pos++;
            }
            if(b==f)ok=true;

                if(p+1<s.length &&  l<f.length && s[p+1]==f[l] && left==false){
                    p++;
                    a+=s[p];
                    l++;
                }
                 else if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                    p--;
                    a+=s[p];
                    l++;
                    left=true;
                }
                else break;
                  pos=l;
            b=a;
            po=p;
            while(po-1>=0 && pos<f.length && s[po-1]==f[pos]){
                po--;
                b+=s[po];
                pos++;
            }
            if(b==f)ok=true;
            }

        }
        if(a==f){
            ok=true;
            break;
        }
    }
    print(ok?"YES":"NO");

}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let str1 = stringArr();
    let str2 = stringArr();
    let obj = {};
    for (let i = 0; i < str1.length; i++) {
      if (str1[i] === str2[0]) {
        if (obj[str2[0]] === undefined) obj[str2[0]] = [];
        obj[str2[0]].push(i);
      }
    }
    if (obj[str2[0]] === undefined) console.log("NO");
    else {
      const helper = (pos) => {
        if (pos === str1.length - 1) {
          let left = pos - 1,
            i = 1;
          while (i < str2.length && left >= 0 && str2[i] === str1[left]) {
            i++;
            left--;
          }
          if (i === str2.length) return true;
          else return false;
        } else {
          let left = pos + 1,
            i = 1;
          while (
            i < str2.length &&
            left < str1.length &&
            str2[i] === str1[left]
          ) {
            left++;
            i++;
          }
          if (i === str2.length) return true;
          let right = left - 2;
          while (i < str2.length && right >= 0 && str1[right] === str2[i]) {
            i++;
            right--;
          }
          if (i === str2.length) return true;
          else return false;
        }
      };
      let k = obj[str2[0]],
        ans = false;
      for (let i = 0; i < k.length; i++) {
        ans = helper(k[i]);
        if (ans === true) break;
      }
      console.log(`${ans === true ? "YES" : "NO"}`);
    }
  }
};
solve();

r=readline
t=+r()
while(t--){
    s=r()
    f=r();n=s.length;m=f.length
    ok=false;
    for(i in s){
        a="";
        if(s[i]==f[0]){
            a+=s[i]; p=i; l=1; left=false;
            while(p<n){
            pos=l;b=a;po=p;
            while(po-1>=0 && pos<m && s[po-1]==f[pos]){ po--; b+=s[po]; pos++;}
            if(b==f)ok=true;
            if(p+1<n &&  l<m  && s[p+1]==f[l] && !left){ p++; a+=s[p]; l++;}
            else break;
          }
        }
        if(a==f){ok=true; break;}
    }
    print(ok?"YES":"NO");
}

r=readline
t=+r()
while(t--)
{
    s=r();
    f=r();
    a="";
    ok=false;
    for(i=0;i<s.length;i++){
        a="";
        b="";
        if(s[i]==f[0]){
            a+=s[i];
            p=i;
            l=1;
            left=false;
            while(true){
                if(p+1<s.length &&  l<f.length && s[p+1]==f[l] && left==false){
                    p++;
                    a+=s[p];
                    l++;
                }
                 else if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                    p--;
                    a+=s[p];
                    l++;
                    left=true;
                }
                else break;
                  pos=l;
            b=a;
            po=p;
            while(po-1>=0 && pos<f.length && s[po-1]==f[pos]){
                po--;
                b+=s[po];
                pos++;
            }
            if(b==f)ok=true;
            }

        }
        if(a==f){
            ok=true;
            break;
        }
    }
    print(ok?"YES":"NO");

}

r=readline
t=+r()
while(t--)
{
    s=r();
    f=r();
    a="";
    ok=false;
    for(i=0;i<s.length;i++){
        a="";
        b="";
        if(s[i]==f[0]){
            a+=s[i];
            p=i;
            l=1;
            left=false;
            while(true){
                if(p+1<s.length &&  l<f.length && s[p+1]==f[l] && left==false){
                    p++;
                    a+=s[p];
                    l++;
                }
                 else if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                    p--;
                    a+=s[p];
                    l++;
                    left=true;
                }
                else break;
            }
            l=1;
            b=s[i];
            p=i;
            if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                p--;
                b+=s[i];
                l++;
            }
            if(b==f)ok=true;
        }
        if(a==f){
            ok=true;
            break;
        }
    }
    print(ok?"YES":"NO");

}

r=readline
t=+r()
while(t--)
{
    s=r();
    f=r();
    a="";
    ok=false;
    for(i=0;i<s.length;i++){
        a="";
        if(s[i]==f[0]){
            a+=s[i];
            p=i;
            l=1;
            left=false;
            while(true){
                if(p+1<s.length &&  l<f.length && s[p+1]==f[l] && left==false){
                    p++;
                    a+=s[p];
                    l++;
                }
                 else if(p-1>=0 && l<f.length && s[p-1]==f[l]){
                    p--;
                    a+=s[p];
                    l++;
                    left=true;
                }
                else break;
            }
        }
        if(a==f){
            ok=true;
            break;
        }
    }
    print(ok?"YES":"NO");

}

for (var q = Number (readline ()); q > 0; q--)
    {
    var s = readline ();
    var t = readline ();
    var b = false;

    for (var i = s.length - 1; i > 0 && !b; i--)
        {
        var z = s.substring (0, i);
        z += (s[i] + z.split ("").reverse ().join (""));

        if (z.indexOf (t) >= 0) { b = true; }
        }

    print (b ? "Yes" : "No");
    }


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const limit = 1e15;
  let [c, min, flag] = [1, Number.MAX_SAFE_INTEGER, true];
  arr.sort((a, b) => a - b);

  while (flag) {
    let count = 0;
    for (let i = 0; i < len; i++) {
      const sqr = Math.pow(c, i);
      if (sqr >= limit) {
        flag = false;
        break;
      }
      const diff = Math.abs(sqr - arr[i]);
      count += diff;
    }
    if (!flag) break;
    min = Math.min(min, count);
    c++;
  }

  console.log(min);
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort((a, b) => a - b)
    let minOperations = null
    let c = 1, op = null
    while (true) {
        let currentOperations = 0
        for (let i = 0, sequenceN = 1; i < N; i++, sequenceN *= c) {
            currentOperations += Math.abs(A[i] - sequenceN)
        }
        if (minOperations !== null && minOperations < currentOperations) {
            break
        }
        minOperations = currentOperations
        c++
    }
    console.log(minOperations)

    process.exit()
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

const getDif = (c, a) => {
  let sum = 0;
  let count = 1;
  a.forEach((_a, idx) => {
    sum += Math.abs(count - _a);
    count *= c;
  });
  return sum;
}

function main() {
  const n = Number(readLine());
  const a = readLine().split(' ').sort((_a, _b) => _a - _b);

  let min = getDif(1, a);
  let min2 = getDif(2, a);
  let i = 2;
  while (min2 < min) {
    min = min2;
    i++;
    min2 = getDif(i, a);
  }
  console.log(min);
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $(), a = $(n).sort(asc)
  if (n > 50) {
    log(a.sum() - n)
  } else {
    let res = a.sum() - n;
    For(1e5, i => {
      if (i ** (n - 1) > 1e14) return 1;
      res = min(res, Arr(n, j => abs(i ** j - a[j])).sum())
    })
    log(res)
  }
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])), A.length); c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperations = null
    let c = 1, op = null
    while (true) {
        let currentOperations = 0
        for (let i = 0, sequenceN = 1; i < N; i++, sequenceN *= c) {
            currentOperations += Math.abs(A[i] - sequenceN)
        }
        if (minOperations === null) {
            minOperations = currentOperations
        } else if (minOperations < currentOperations) {
            break
        }
        minOperations = currentOperations
        c++
    }
    console.log(minOperations)

    process.exit()
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])), A.length); c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        if (c === 0) {
            expectedA[0] = 0
        }
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.ceil(Math.sqrt(A[A.length - 1])); c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])), A.length * A.length); c > 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])) + 1, A.length * A.length); c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = A.length; c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.ceil(Math.sqrt(A[A.length - 1])); c > 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])), A.length * A.length); c >= 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let inputString = ''
let currentLine = 0

process.stdin.on('data', inputStdin => {
    inputString += inputStdin
});

process.stdin.on('end', () => {
    inputString = inputString.split(/\n/)
    main()
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
    const N = Number(readLine())
    const A = readLine().split(' ').map(value => Number(value))
    A.sort()
    let minOperation = null
    for (let c = Math.max(Math.ceil(Math.sqrt(A[A.length - 1])), A.length); c > 0; c--) {
        const expectedA = new Array(N).fill(0).map(((value, index) => Math.pow(c, index)))
        let currentMinOperation = 0
        for (let i = 0; i < N; i++) {
            currentMinOperation += Math.abs(expectedA[i] - A[i])
        }
        if (minOperation === null) {
            minOperation = currentMinOperation
        } else if (minOperation > currentMinOperation) {
            minOperation = currentMinOperation
        }
    }
    console.log(minOperation)
}


const readline = require('readline');
const { randomBytes } = require('crypto');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

// compute('1 2 2', 3)

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>max&&r!=0){
            max = remainStats[r]
            maxi = r
        }
        if(remainStats[r]==max){
            if(r!=0&&r<maxi){
                maxi = r
            }
        }
    }
    // console.log(remainStats)
    // console.log(maxi, max)

    if(max==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}

function solve() {
   var nk = read().split(' ').map(Number);
   var n = nk[0];
   var k = nk[1];
   var amap = {};
   var maxA = 0;
   var maxCount = 0;
   var a = read().split(' ');
   for (var i = 0; i < n; i++) {
      var x = Number(a[i]) % k;
      if (x === 0) {
         continue;
      }
      x = k - x;
      if (amap[x]) {
         amap[x]++;
      } else {
         amap[x] = 1;
      }
      if (amap[x] > maxCount || amap[x] === maxCount && x > maxA) {
         maxCount = amap[x];
         maxA = x;
      }
   }
   if (maxCount === 0) {
      write(0);
      return;
   }
   write((maxCount - 1) * k + maxA + 1);

}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>max&&r!=0){
            max = remainStats[r]
            maxi = r
        }
    }

    // var max = 0
    // var maxi = 0
    // for(var i=1;i<k;i++){
    //     if(remainStats[i]>max){
    //         max = remainStats[i]
    //         maxi = i
    //     }
    // }
    // console.log(max, maxi)
    if(max==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>max&&r!=0){
            max = remainStats[r]
            maxi = r
        }
    }

    // var max = 0
    // var maxi = 0
    // for(var i=1;i<k;i++){
    //     if(remainStats[i]>max){
    //         max = remainStats[i]
    //         maxi = i
    //     }
    // }
    console.log(max, maxi)
    if(max==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>=max&&r > 0&&r<maxi){
            max = remainStats[r]
            maxi = r
        }
    }

    if(max==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>max){
            max = remainStats[r]
            maxi = r
        }
    }

    // var max = 0
    // var maxi = 0
    // for(var i=1;i<k;i++){
    //     if(remainStats[i]>max){
    //         max = remainStats[i]
    //         maxi = i
    //     }
    // }
    console.log(max, maxi)
    if(max==0||maxi==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}

const readline = require('readline');
const { randomBytes } = require('crypto');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lineCount = 0
var testCount = 0
var outputStr = ''
var tempk = 0

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        tempk = parseInt(input.split(' ')[1])
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input, tempk) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input, tempk) + '\n'
    }
    lineCount++
});

function compute(str, k) {
    var list = str.split(' ')
    var remainStats = []
    var max = 0
    var maxi = 0
    for(var item of list){
        var r = parseInt(item) % k
        remainStats[r] = remainStats[r]?remainStats[r]+1:1
        if(remainStats[r]>=max&&r > 0){
            max = remainStats[r]
            if(maxi==0||r<maxi)
                maxi = r
        }
    }

    if(max==0){
        return 0
    }
    return ((max-1)*k+(k - maxi)+1)
}


var a = readline();
var b = get(a);
if (b.length == 0) {
    print(a);
} else if (b.length % 2 != 0) {
    print(":(");
} else {
    var sub = b.substring(0, b.length / 2);
    if (a.substring(a.length - sub.length, a.length) === sub) {
        print(a.substring(0, a.length - sub.length));
    } else {
        print(":(");
    }
}

function get(a) {
    var ret = "";
    for (var i = 0; i < a.length; ++i) {
        ret += a[i] != "a" ? a[i] : "";
    }
    return ret;
}

let z = '';
process.stdin.on('data', c => z += c);
process.stdin.on('end', () => {
    const {
        EOL
    } = require('os');
    let input = z.split(EOL)[0]
    let noA = '';
    for (const item of input) {
        if (item != 'a')
            noA += item;
    }
    if(noA.length===0)
    console.log(input);
    else if(noA.slice(0,parseInt(noA.length/2))===noA.slice(parseInt(noA.length/2)) && input.slice(input.length-(noA.length/2)).match(/[a]/g)===null){
        console.log(input.slice(0, (input.length - (noA.length / 2))));
    }
    else
    console.log(':(');
});

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function main (s) {
  let s1 = "";
  let s2 = ""
  for (i = 0; i < s.length; i++) {
    const char = s[i];
    s1 += char;
    if (char !== "a") {
      s2 += char;
    }

    const s3 = s.slice(i+1);
    if (s2 === s3 && s3.indexOf("a") === -1) {
      return s1;
    }
  }
  return ":(";
}
/*
function main2(s) {
  start = 0;
  end = s.length - 1;
  let result = "";
  let result_without_a = "";
  while (true) {
    if (s[start] === "a") {
      result += s[start];
      continue;
    } else {
      result_without_a += s[start];
    }

  }
}
*/

rl.on('line', (str) => {
  console.log(main(str));
  rl.close();
});
/*
rl.on('line', (str) => {
  let s = str.split("");
  if (s.every(char => char === 'a')) {
    result = str;
  } else {
    if (s[s.length -1] === "a"){
      result = ":(";
    } else {
      let new_s = s.filter(char => char !== 'a');
    if (new_s.length % 2) {
      result = ":(";
    } else {
        const medium = new_s.length / 2;
        const s2 = new_s.slice(medium).join("");
        if (new_s.slice(0, medium).join("") === s2) {
          const pos = str.lastIndexOf(s2);
          result = s.slice(0, pos).join("");
        } else {
          result = ":(";
        }
      }
    }

  }
  console.log(result);
  rl.close();

});
*/

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('line', (str) => {
  let s = str.split("");
  if (s.every(char => char === 'a')) {
    result = str;
  } else {
    if (s[s.length -1] === "a"){
      result = ":(";
    } else {
      let new_s = s.filter(char => char !== 'a');
    if (new_s.length % 2) {
      result = ":(";
    } else {
        const medium = new_s.length / 2;
        const s2 = new_s.slice(medium).join("");
        if (new_s.slice(0, medium).join("") === s2) {
          const pos = str.lastIndexOf(s2);
          result = s.slice(0, pos).join("");
        } else {
          result = ":(";
        }
      }
    }

  }
  console.log(result);
  rl.close();

});

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('line', (str) => {
  let s = str.split("");
  if (s.every(char => char === 'a')) {
    result = str;
  } else {
    if (s[s.length -1] === "a"){
      result = ":(";
    } else {
      if (str.indexOf("a") < 0) {
        result = str;
      } else {
        let new_s = s.filter(char => char !== 'a');
        if (new_s.length % 2) {
          result = ":(";
        } else {
            const medium = new_s.length / 2;
            const s2 = new_s.slice(medium).join("");
            if (new_s.slice(0, medium).join("") === s2) {
              const pos = str.lastIndexOf(s2);
              result = s.slice(0, pos).join("");
            } else {
              result = ":(";
            }
          }
      }

    }

  }
  console.log(result);
  rl.close();

});

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('line', (str) => {
  let s = str.split("");
  if (s.every(char => char === 'a')) {
    result = str;
  } else {
    if (s[s.length -1] === "a"){
      result = ":(";
    } else {
      if (str.indexOf("a") < 0) {
        result = "";
      } else {
        let new_s = s.filter(char => char !== 'a');
        if (new_s.length % 2) {
          result = ":(";
        } else {
            const medium = new_s.length / 2;
            const s2 = new_s.slice(medium).join("");
            if (new_s.slice(0, medium).join("") === s2) {
              const pos = str.lastIndexOf(s2);
              result = s.slice(0, pos).join("");
            } else {
              result = ":(";
            }
          }
      }

    }

  }
  console.log(result);
  rl.close();

});

let z = '';
process.stdin.on('data', c => z += c);
process.stdin.on('end', () => {
    const {
        EOL
    } = require('os');
    let input = z.split(EOL)[0]
    let noA = '';
    for (const item of input) {
        if (item != 'a')
            noA += item;
    }

    if(noA.slice(0,parseInt(noA.length/2))===noA.slice(parseInt(noA.length/2))){
        console.log(input.slice(0, (input.length - (noA.length / 2))));
        return 0;
    }
    console.log(':(');
});

var a = readline();
var b = get(a);
if (includes(a,'a')) {
    if (a == b) {
        print(a);
    } else {
        if (b.length % 2 ==0) {
            var mid = b.length/2;
            if (b.substring(0,mid) === b.substring(mid,b.length)) {
               if (isValid(a.substring(0,a.length-mid), a)) {
                    print(a.substring(0,a.length-mid));
               } else {
                   print(':(');
               }
            } else {
                print(':(');
            }
        } else {
            print(':(');
        }
    }
} else {
    print(':(');
}

function isValid(a,b) {
    var val ="";
    for (var i = 0; i <a.length; ++i) {
        val += a[i] === 'a' ? '' : a[i];
    }
    return a.concat(val) === b;
}

function get(word) {
    var val = "";
    for (var i = 0; i < word.length; i++) {
        val += word[i] === 'a' ? '' : word[i];
    }
    return val;
}

function includes(word,x) {
    for(var i =0; i < word.length; ++i) {
        if (word[i] === x) {
            return true;
        }
    }
    return false;
}

var a = readline();
var last = "";
var first = "";
for (var i = a.length - 1; i >= 0; --i) {
    if (a[i] != 'a') {
        last += a[i];
    } else {
        last = last.split("").reverse().join("");
        for (var j = 0; j < i; ++j) {
            first += a[j] != 'a' ? a[j] : "";
        }
        break;
    }
}
var b = first + last;
if (b.length % 2 == 0) {
    var mid = b.length / 2;
    var f = b.substring(0, mid);
    var l = b.substring(mid, b.length);
    if (f == l) {
        print(a.substring(0, a.length - f.length));
    } else {
        print(":(");
    }
} else {
    print(":(");
}

var a = readline();
var last = "";
var first = "";
for (var i = a.length - 1; i >= 0; --i) {
    if (a[i] != 'a') {
        last += a[i];
    } else {
        last = last.split("").reverse().join("");
        for (var j = 0; j < i; ++j) {
            first += a[j] != 'a' ? a[j] : "";
        }
        break;
    }
}
var b = first + last;
if ((last.length == 0 && first.length != 0)) {
    print(":(");
}
else if (b.length % 2 == 0) {
    var mid = b.length / 2;
    var f = b.substring(0, mid);
    var l = b.substring(mid, b.length);
    if (f == l) {
        print(a.substring(0, a.length - f.length));
    } else {
        print(":(");
    }
} else {
    print(":(");
}