You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, numbered from $$$1$$$ to $$$n$$$. You can perform the following operation no more than $$$3n$$$ times:  choose three integers $$$i$$$, $$$j$$$ and $$$x$$$ ($$$1 \le i, j \le n$$$; $$$0 \le x \le 10^9$$$);  assign $$$a_i := a_i - x \cdot i$$$, $$$a_j := a_j + x \cdot i$$$. After each operation, all elements of the array should be non-negative.Can you find a sequence of no more than $$$3n$$$ operations after which all elements of the array are equal?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case print the answer to it as follows:   if there is no suitable sequence of operations, print $$$-1$$$;  otherwise, print one integer $$$k$$$ ($$$0 \le k \le 3n$$$) — the number of operations in the sequence. Then print $$$k$$$ lines, the $$$m$$$-th of which should contain three integers $$$i$$$, $$$j$$$ and $$$x$$$ ($$$1 \le i, j \le n$$$; $$$0 \le x \le 10^9$$$) for the $$$m$$$-th operation.  If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize $$$k$$$.

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'))
}

'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 = 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();


You have a string $$$s$$$ and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i + 1$$$. Of course, moving the chip to the right is impossible if it is already in the last position.After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i - 1$$$. Of course, moving the chip to the left is impossible if it is already in the first position.When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if $$$s$$$ is abcdef, you place the chip onto the $$$3$$$-rd character, move it to the right $$$2$$$ times and then move it to the left $$$3$$$ times, you write down the string cdedcb.You are given two strings $$$s$$$ and $$$t$$$. Your task is to determine whether it's possible to perform the described operations with $$$s$$$ so that you write down the string $$$t$$$ as a result.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains the string $$$s$$$ ($$$1 \le |s| \le 500$$$), the second line contains the string $$$t$$$ ($$$1 \le |t| \le 2 \cdot |s| - 1$$$). Both strings consist of lowercase English characters. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$500$$$.

For each test case, print "YES" if you can obtain the string $$$t$$$ by performing the process mentioned in the statement with the string $$$s$$$, or "NO" if you cannot. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

6
abcdef
cdedcb
aaa
aaaaa
aab
baaa
ab
b
abcdef
abcdef
ba
baa

NoteConsider the examples.The first test case is described in the statement.In the second test case, you can place the chip on the $$$1$$$-st position, move it twice to the right, and then move it twice to the left.In the fourth test case, you can place the chip on the $$$2$$$-nd position, and then don't move it at all.In the fifth test case, you can place the chip on the $$$1$$$-st position, move it $$$5$$$ times to the right, and then finish the process.

"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");

}

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 = 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's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to:  Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then  Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$.

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;
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);
}

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


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations:  Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$).  Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$$$) — the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.

NoteConsider the first test case of the example:  $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$;  $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$;  $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$;  $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$;  $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$;  $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$;  $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once.

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 { 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)
}

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


Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all "a" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique.

The first line of input contains a string $$$t$$$ ($$$1 \leq |t| \leq 10^5$$$) consisting of lowercase English letters.

Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

NoteIn the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc".

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

});
*/

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(':(');
});

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;
}

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(":(");
}