const solve = (n, x, a) => {
    a = a.map(x => [x, 1]);
    let res = 0;
    let flag = true;
    for (let i = 0; i < a.length; i++) {
        let tmp = a[i];
        res += tmp[0] * tmp[1];
        if (tmp[0] % x) flag = false;
        if (flag) a.push([parseInt(tmp[0] / x), tmp[1] * x]);
    }
    console.log(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i + 1]);
            i += 2;
        }
    });
};

main()

"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, x] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n; i++) {
      let obj = { val: arr[i], m: 1 };
      arr[i] = obj;
    }
    let sum = 0,
      flag = true;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].val % x) flag = false;
      if (flag) {
        let obj = { val: arr[i].val / x, m: arr[i].m * x };
        arr.push(obj);
      }
      sum += arr[i].val * arr[i].m;
    }
    console.log(sum);
  }
};
solve();

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
	for (var a = arguments, r = a[0], i = a.length; --i; )
		r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
	return r;
}
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);
	u %= MOD;
	return u < 0 ? u + MOD : u;
}
function pow(base, n) {
	if (n === 0) return 1;
	let p = pow(base, Math.floor(n / 2));
	let res = mul(mod(p), mod(p));
	if (n % 2 === 1) res = mul(mod(res), base);
	return res;
}
function highestOneBit(i) {
	i |= i >> 1;
	i |= i >> 2;
	i |= i >> 4;
	i |= i >> 8;
	i |= i >> 16;
	return i - (i >>> 1);
}
function permutation(arr, len, store = '', permutations = []) {
	if (store.length === len) {
		permutations.push(store);
		return;
	}
	for (let i = 0; i < arr.length; i++) {
		const newArr = [...arr];
		const newChar = newArr.splice(i, 1);
		permutation(newArr, len, store.concat(newChar), permutations);
	}
	return permutations;
}

function main() {
	let t = +readLine();
	while (t--) {
		const [len, x] = readLine().split(' ').map(Number);
		let sum = 0;
		const arr = readLine()
			.split(' ')
			.map((n) => {
				n = Number(n);
				sum += n;
				return n;
			});
		const store = [];
		let [minIndex, min] = [Infinity, Infinity];
		for (let i = 0; i < len; i++) {
			let [count, n] = [0, arr[i]];
			while (n % x === 0) {
				n = n / x;
				count++;
			}
			if (count < min) {
				min = count;
				minIndex = i;
			}
		}
		sum += sum * min;
		for (let i = 0; i < minIndex; i++) sum += arr[i];

		console.log(sum);
	}
}

let i = '';
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);

    const t = parseInt(lines[0]);

    for (let i = 1; i <= t * 2; i += 2) {
        let split = lines[i].split(' ');
        const n = parseInt(split[0]);
        const x = parseInt(split[1]);

        const arr = lines[i + 1].split(' ').map(num => parseInt(num));

        solve(n, x, arr);
    }
});

function solve(n, x, arr) {
    let sum = 0;
    let coeff = [];

    for (let i = 0; i < n; i++) {
        sum += arr[i];
        coeff[i] = 1;
    }

    let i = 0;

    while (i < arr.length) {
        if (arr[i] % x === 0) {
            sum += arr[i] * coeff[i];
            arr.push(Math.floor(arr[i] / x));
            coeff.push(coeff[i] * x);
        } else {
            break;
        }

        i++;
    }

    console.log(sum);
}

// Generated by CoffeeScript 2.4.1
var A, _, a, b, i, iters, j, k, l, len, min, mult, mults, n, nr, nrs, nx, ref, ref1, sum, x;

nrs = function() {
  var i, j, len, ref, results;
  ref = readline().split(' ');
  results = [];
  for (j = 0, len = ref.length; j < len; j++) {
    i = ref[j];
    results.push(parseInt(i));
  }
  return results;
};

nr = function() {
  return nrs()[0];
};

function zip(a, b) {
  var arr = [];
  for (var key in a) arr.push([a[key], b[key]]);
  return arr;
}
;

min = function(arr) {
  var best, item, j, len;
  best = arr[0];
  for (j = 0, len = arr.length; j < len; j++) {
    item = arr[j];
    if (item < best) {
      best = item;
    }
  }
  return best;
};

for (_ = j = 0, ref = nr(); (0 <= ref ? j < ref : j > ref); _ = 0 <= ref ? ++j : --j) {
  nx = nrs();
  n = nx[0];
  x = nx[1];
  A = nrs();
  a = A.shift();
  mult = 0;
  mults = [];
  while (a % Math.pow(x, mult + 1) === 0) {
    mult += 1;
  }
  mults.push(mult);
  for (k = 0, len = A.length; k < len; k++) {
    b = A[k];
    while (b % Math.pow(x, mult)) {
      mult -= 1;
    }
    mults.push(mult);
  }
  iters = 1 + min(mults);
  A.unshift(a);
  sum = 0;
  for (i = l = 0, ref1 = A.length; (0 <= ref1 ? l < ref1 : l > ref1); i = 0 <= ref1 ? ++l : --l) {
    sum += A[i] * (Math.min(iters, mults[i]) + 1);
  }
  print(sum);
}

//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia2lzc3pvdHMuanMiLCJzb3VyY2VSb290IjoiLi4iLCJzb3VyY2VzIjpbImNvZmZlZVxca2lzc3pvdHMuY29mZmVlIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxJQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsS0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLEtBQUEsRUFBQSxDQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxFQUFBLEVBQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxHQUFBLEVBQUE7O0FBQUEsR0FBQSxHQUFNLFFBQUEsQ0FBQSxDQUFBO0FBQUcsTUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLEdBQUEsRUFBQSxHQUFBLEVBQUE7QUFBVztBQUFBO0VBQUEsS0FBQSxxQ0FBQTs7aUJBQVgsUUFBQSxDQUFTLENBQVQ7RUFBVyxDQUFBOztBQUFkOztBQUNOLEVBQUEsR0FBSyxRQUFBLENBQUEsQ0FBQTtTQUFHLEdBQUEsQ0FBQSxDQUFNLENBQUEsQ0FBQTtBQUFUOztBQUVMOzs7Ozs7OztBQVFBLEdBQUEsR0FBTSxRQUFBLENBQUMsR0FBRCxDQUFBO0FBQ0wsTUFBQSxJQUFBLEVBQUEsSUFBQSxFQUFBLENBQUEsRUFBQTtFQUFBLElBQUEsR0FBTyxHQUFJLENBQUEsQ0FBQTtFQUNYLEtBQUEscUNBQUE7O0lBQ0MsSUFBRyxJQUFBLEdBQU8sSUFBVjtNQUFvQixJQUFBLEdBQUssS0FBekI7O0VBREQ7U0FFQTtBQUpLOztBQU1OLEtBQVMsK0VBQVQ7RUFDQyxFQUFBLEdBQUssR0FBQSxDQUFBO0VBQ0wsQ0FBQSxHQUFJLEVBQUcsQ0FBQSxDQUFBO0VBQ1AsQ0FBQSxHQUFJLEVBQUcsQ0FBQSxDQUFBO0VBQ1AsQ0FBQSxHQUFJLEdBQUEsQ0FBQTtFQUVKLENBQUEsR0FBSSxDQUFDLENBQUMsS0FBRixDQUFBO0VBQ0osSUFBQSxHQUFPO0VBQ1AsS0FBQSxHQUFRO0FBQ1IsU0FBTSxDQUFBLEdBQUksSUFBSSxDQUFDLEdBQUwsQ0FBUyxDQUFULEVBQVcsSUFBQSxHQUFLLENBQWhCLENBQUosS0FBMEIsQ0FBaEM7SUFDQyxJQUFBLElBQU07RUFEUDtFQUVBLEtBQUssQ0FBQyxJQUFOLENBQVcsSUFBWDtFQUNBLEtBQUEsbUNBQUE7O0FBQ0MsV0FBTSxDQUFBLEdBQUksSUFBSSxDQUFDLEdBQUwsQ0FBUyxDQUFULEVBQVcsSUFBWCxDQUFWO01BQ0MsSUFBQSxJQUFRO0lBRFQ7SUFFQSxLQUFLLENBQUMsSUFBTixDQUFXLElBQVg7RUFIRDtFQUlBLEtBQUEsR0FBUSxDQUFBLEdBQUksR0FBQSxDQUFJLEtBQUo7RUFDWixDQUFDLENBQUMsT0FBRixDQUFVLENBQVY7RUFFQSxHQUFBLEdBQU07RUFDTixLQUFTLHdGQUFUO0lBQ0MsR0FBQSxJQUFPLENBQUUsQ0FBQSxDQUFBLENBQUYsR0FBTyxDQUFDLElBQUksQ0FBQyxHQUFMLENBQVMsS0FBVCxFQUFlLEtBQU0sQ0FBQSxDQUFBLENBQXJCLENBQUEsR0FBeUIsQ0FBMUI7RUFEZjtFQUVBLEtBQUEsQ0FBTSxHQUFOO0FBdEJEIiwic291cmNlc0NvbnRlbnQiOlsibnJzID0gLT4gcGFyc2VJbnQgaSBmb3IgaSBpbiByZWFkbGluZSgpLnNwbGl0ICcgJ1xyXG5uciA9IC0+IG5ycygpWzBdXHJcblxyXG5gYGBcclxuZnVuY3Rpb24gemlwKGEsIGIpIHtcclxuICB2YXIgYXJyID0gW107XHJcbiAgZm9yICh2YXIga2V5IGluIGEpIGFyci5wdXNoKFthW2tleV0sIGJba2V5XV0pO1xyXG4gIHJldHVybiBhcnI7XHJcbn1cclxuYGBgXHJcblxyXG5taW4gPSAoYXJyKSAtPlxyXG5cdGJlc3QgPSBhcnJbMF1cclxuXHRmb3IgaXRlbSBpbiBhcnJcclxuXHRcdGlmIGl0ZW0gPCBiZXN0IHRoZW4gYmVzdD1pdGVtXHJcblx0YmVzdFxyXG5cclxuZm9yIF8gaW4gWzAuLi5ucigpXVxyXG5cdG54ID0gbnJzKClcclxuXHRuID0gbnhbMF1cclxuXHR4ID0gbnhbMV1cclxuXHRBID0gbnJzKClcclxuXHJcblx0YSA9IEEuc2hpZnQoKVxyXG5cdG11bHQgPSAwXHJcblx0bXVsdHMgPSBbXVxyXG5cdHdoaWxlIGEgJSBNYXRoLnBvdyh4LG11bHQrMSkgPT0gMFxyXG5cdFx0bXVsdCs9MVxyXG5cdG11bHRzLnB1c2ggbXVsdFxyXG5cdGZvciBiIGluIEFcclxuXHRcdHdoaWxlIGIgJSBNYXRoLnBvdyh4LG11bHQpXHJcblx0XHRcdG11bHQgLT0gMVxyXG5cdFx0bXVsdHMucHVzaCBtdWx0XHJcblx0aXRlcnMgPSAxICsgbWluIG11bHRzXHJcblx0QS51bnNoaWZ0IGFcclxuXHJcblx0c3VtID0gMFxyXG5cdGZvciBpIGluIFswLi4uQS5sZW5ndGhdXHJcblx0XHRzdW0gKz0gQVtpXSAqIChNYXRoLm1pbihpdGVycyxtdWx0c1tpXSkrMSlcclxuXHRwcmludCBzdW1cclxuIl19
//# sourceURL=c:\github\2021\008-CodeForces-1100\1471B\coffee\kisszots.coffee

// Generated by CoffeeScript 2.4.1
var A, _, a, b, iters, j, k, l, len, len1, min, mult, multb, mults, n, nr, nrs, nx, ref, ref1, sum, x;

nrs = function() {
  var i, j, len, ref, results;
  ref = readline().split(' ');
  results = [];
  for (j = 0, len = ref.length; j < len; j++) {
    i = ref[j];
    results.push(parseInt(i));
  }
  return results;
};

nr = function() {
  return nrs()[0];
};

function zip(a, b) {
  var arr = [];
  for (var key in a) arr.push([a[key], b[key]]);
  return arr;
}
;

min = function(arr) {
  var best, item, j, len;
  best = arr[0];
  for (j = 0, len = arr.length; j < len; j++) {
    item = arr[j];
    if (item < best) {
      best = item;
    }
  }
  return best;
};

for (_ = j = 0, ref = nr(); (0 <= ref ? j < ref : j > ref); _ = 0 <= ref ? ++j : --j) {
  nx = nrs();
  n = nx[0];
  x = nx[1];
  A = nrs();
  a = A.shift();
  mult = 0;
  mults = [];
  while (a % Math.pow(x, mult + 1) === 0) {
    mult += 1;
  }
  mults.push(mult);
  for (k = 0, len = A.length; k < len; k++) {
    b = A[k];
    while (b % Math.pow(x, mult)) {
      mult -= 1;
    }
    mults.push(mult);
  }
  iters = 1 + min(mults);
  A.unshift(a);
  sum = 0;
  ref1 = zip(mults, A);
  for (l = 0, len1 = ref1.length; l < len1; l++) {
    multb = ref1[l];
    mult = multb[0];
    b = multb[1];
    sum += b * (Math.min(iters, mult) + 1);
  }
  print(sum);
}

//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia2lzc3pvdHMuanMiLCJzb3VyY2VSb290IjoiLi4iLCJzb3VyY2VzIjpbImNvZmZlZVxca2lzc3pvdHMuY29mZmVlIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxJQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxLQUFBLEVBQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxDQUFBLEVBQUEsR0FBQSxFQUFBLElBQUEsRUFBQSxHQUFBLEVBQUEsSUFBQSxFQUFBLEtBQUEsRUFBQSxLQUFBLEVBQUEsQ0FBQSxFQUFBLEVBQUEsRUFBQSxHQUFBLEVBQUEsRUFBQSxFQUFBLEdBQUEsRUFBQSxJQUFBLEVBQUEsR0FBQSxFQUFBOztBQUFBLEdBQUEsR0FBTSxRQUFBLENBQUEsQ0FBQTtBQUFHLE1BQUEsQ0FBQSxFQUFBLENBQUEsRUFBQSxHQUFBLEVBQUEsR0FBQSxFQUFBO0FBQVc7QUFBQTtFQUFBLEtBQUEscUNBQUE7O2lCQUFYLFFBQUEsQ0FBUyxDQUFUO0VBQVcsQ0FBQTs7QUFBZDs7QUFDTixFQUFBLEdBQUssUUFBQSxDQUFBLENBQUE7U0FBRyxHQUFBLENBQUEsQ0FBTSxDQUFBLENBQUE7QUFBVDs7QUFFTDs7Ozs7Ozs7QUFRQSxHQUFBLEdBQU0sUUFBQSxDQUFDLEdBQUQsQ0FBQTtBQUNMLE1BQUEsSUFBQSxFQUFBLElBQUEsRUFBQSxDQUFBLEVBQUE7RUFBQSxJQUFBLEdBQU8sR0FBSSxDQUFBLENBQUE7RUFDWCxLQUFBLHFDQUFBOztJQUNDLElBQUcsSUFBQSxHQUFPLElBQVY7TUFBb0IsSUFBQSxHQUFLLEtBQXpCOztFQUREO1NBRUE7QUFKSzs7QUFNTixLQUFTLCtFQUFUO0VBQ0MsRUFBQSxHQUFLLEdBQUEsQ0FBQTtFQUNMLENBQUEsR0FBSSxFQUFHLENBQUEsQ0FBQTtFQUNQLENBQUEsR0FBSSxFQUFHLENBQUEsQ0FBQTtFQUNQLENBQUEsR0FBSSxHQUFBLENBQUE7RUFFSixDQUFBLEdBQUksQ0FBQyxDQUFDLEtBQUYsQ0FBQTtFQUNKLElBQUEsR0FBTztFQUNQLEtBQUEsR0FBUTtBQUNSLFNBQU0sQ0FBQSxHQUFJLElBQUksQ0FBQyxHQUFMLENBQVMsQ0FBVCxFQUFXLElBQUEsR0FBSyxDQUFoQixDQUFKLEtBQTBCLENBQWhDO0lBQ0MsSUFBQSxJQUFNO0VBRFA7RUFFQSxLQUFLLENBQUMsSUFBTixDQUFXLElBQVg7RUFDQSxLQUFBLG1DQUFBOztBQUNDLFdBQU0sQ0FBQSxHQUFJLElBQUksQ0FBQyxHQUFMLENBQVMsQ0FBVCxFQUFXLElBQVgsQ0FBVjtNQUNDLElBQUEsSUFBUTtJQURUO0lBRUEsS0FBSyxDQUFDLElBQU4sQ0FBVyxJQUFYO0VBSEQ7RUFJQSxLQUFBLEdBQVEsQ0FBQSxHQUFJLEdBQUEsQ0FBSSxLQUFKO0VBQ1osQ0FBQyxDQUFDLE9BQUYsQ0FBVSxDQUFWO0VBRUEsR0FBQSxHQUFNO0FBQ047RUFBQSxLQUFBLHdDQUFBOztJQUNDLElBQUEsR0FBTyxLQUFNLENBQUEsQ0FBQTtJQUNiLENBQUEsR0FBSSxLQUFNLENBQUEsQ0FBQTtJQUNWLEdBQUEsSUFBTyxDQUFBLEdBQUksQ0FBQyxJQUFJLENBQUMsR0FBTCxDQUFTLEtBQVQsRUFBZSxJQUFmLENBQUEsR0FBcUIsQ0FBdEI7RUFIWjtFQUlBLEtBQUEsQ0FBTSxHQUFOO0FBeEJEIiwic291cmNlc0NvbnRlbnQiOlsibnJzID0gLT4gcGFyc2VJbnQgaSBmb3IgaSBpbiByZWFkbGluZSgpLnNwbGl0ICcgJ1xyXG5uciA9IC0+IG5ycygpWzBdXHJcblxyXG5gYGBcclxuZnVuY3Rpb24gemlwKGEsIGIpIHtcclxuICB2YXIgYXJyID0gW107XHJcbiAgZm9yICh2YXIga2V5IGluIGEpIGFyci5wdXNoKFthW2tleV0sIGJba2V5XV0pO1xyXG4gIHJldHVybiBhcnI7XHJcbn1cclxuYGBgXHJcblxyXG5taW4gPSAoYXJyKSAtPlxyXG5cdGJlc3QgPSBhcnJbMF1cclxuXHRmb3IgaXRlbSBpbiBhcnJcclxuXHRcdGlmIGl0ZW0gPCBiZXN0IHRoZW4gYmVzdD1pdGVtXHJcblx0YmVzdFxyXG5cclxuZm9yIF8gaW4gWzAuLi5ucigpXVxyXG5cdG54ID0gbnJzKClcclxuXHRuID0gbnhbMF1cclxuXHR4ID0gbnhbMV1cclxuXHRBID0gbnJzKClcclxuXHJcblx0YSA9IEEuc2hpZnQoKVxyXG5cdG11bHQgPSAwXHJcblx0bXVsdHMgPSBbXVxyXG5cdHdoaWxlIGEgJSBNYXRoLnBvdyh4LG11bHQrMSkgPT0gMFxyXG5cdFx0bXVsdCs9MVxyXG5cdG11bHRzLnB1c2ggbXVsdFxyXG5cdGZvciBiIGluIEFcclxuXHRcdHdoaWxlIGIgJSBNYXRoLnBvdyh4LG11bHQpXHJcblx0XHRcdG11bHQgLT0gMVxyXG5cdFx0bXVsdHMucHVzaCBtdWx0XHJcblx0aXRlcnMgPSAxICsgbWluIG11bHRzXHJcblx0QS51bnNoaWZ0IGFcclxuXHJcblx0c3VtID0gMFxyXG5cdGZvciBtdWx0YiBpbiB6aXAgbXVsdHMsQVxyXG5cdFx0bXVsdCA9IG11bHRiWzBdXHJcblx0XHRiID0gbXVsdGJbMV1cclxuXHRcdHN1bSArPSBiICogKE1hdGgubWluKGl0ZXJzLG11bHQpKzEpXHJcblx0cHJpbnQgc3VtXHJcbiJdfQ==
//# sourceURL=c:\github\2021\008-CodeForces-1100\1471B\coffee\kisszots.coffee

"use strict"

let iter = parseInt(readline());

for(let i = 0; i < iter; i++){
    let input = readline().split(" ").map(x => parseInt(x));
    let n = input[0];
    let x = input[1];
    let arr = readline().split(" ").map(x => parseInt(x));
    let result = 0;
    let iters = [];

    for(let j = 0; j < n; j++){
        iters.push(getIter(arr[j], x));
    }
    let minIter = findMin(iters);
    let index = iters.indexOf(minIter);
    print(sumArr(arr.slice(0, index)) * (minIter + 2) + sumArr(arr.slice(index, arr.length)) * (minIter + 1))
}

function getIter(num, x){
    let i;
    for(i = 0; num % x === 0; i++){
        num /= x;
    }
    return i;
}

function sumArr(arr){
    let res = 0;
    for(let i = 0; i < arr.length; i++){
        res += arr[i];
    }
    return res;
}

function findMin(arr){
    let res = arr[0];
    for(let i = 1; i < arr.length; i++){
        if(arr[i] < res){
            res = arr[i];
        }
    }
    return res;
}

const solve = (n, x, a) => {
    let res = 0;
    let flag = true;
    for (let i = 0; i < a.length; i++) {
        let tmp = a[i];
        res += tmp[0] * tmp[1];
        if (tmp[0] % x) flag = false;
        if (flag) a.push([parseInt(tmp[0] / x), tmp[1] * x]);
    }
    console.log(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => [Number(x), 1]));
    });
    rl.on('close', () => {
        let t = input[0][0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0][0], input[i][1][0], input[i + 1])
            i += 2;
        }
    });
};

main()

const solve = (n, x, a) => {
    let res = 0;
    let flag = true;
    for (let i = 0; i < a.length; i++) {
        let tmp = a[i];
        res += tmp[0] * tmp[1];
        if (tmp[0] % x) flag = false;
        if (flag) a.push([parseInt(tmp[0] / x), tmp[1] * x]);
    }
    console.log(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => [Number(x), 1]));
    });
    rl.on('close', () => {
        let t = input[0][0][0];
        let i = 1;
        while (t--) {
            let data = input.slice(i, i + 2);
            solve(data[0][0][0], data[0][1][0], data[1]);
            i += 2;
        }
    });
};

main()

const solve = (n, x, a) => {
    a = a.map(x => [x, 1]);
    let res = 0;
    let flag = true;
    for (let i = 0; i < a.length; i++) {
        let tmp = a[i];
        res += tmp[0] * tmp[1];
        if (tmp[0] % x) flag = false;
        if (flag) a.push([parseInt(tmp[0] / x), tmp[1] * x]);
    }
    console.log(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            let data = input.slice(i, i + 2);
            solve(data[0][0], data[0][1], data[1]);
            i += 2;
        }
    });
};

main()

'use strict';

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.trim().split('\n').map(string => {
    return string.trim();
  });

  main()
});

function readline() {
  return inputString[currentLine++]
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let testCases = readline()
  while(testCases--)
    solve()
}

// function to solve problems
function solve (){
  let [n,q] = readline().split(' ').map(x => +x),
    counts = [],
    nums = readline().split(' ').map(x => {
      counts.push(1)
      return +x
    }),
    sum = 0,
    num = 0
  let i=0
  while(nums[i] % q == 0) {
    num = parseInt(nums[i]/q)
    nums.push(num)
    counts.push(q * counts[i])
    sum += nums[i] * counts[i]
    i++
  }
  while (i < nums.length) {
    sum += nums[i] * counts[i]
    i++
  }
  console.log(sum)
  // for (let i=0; i<arr.length; i++) {
  //   let [arrKey, arrValue] = Object.entries(arr)[i]
  //   let [num,count] = Object.entries(arrValue)[0]
  //   if (num % q == 0) {
  //     let obj2 = {}
  //     obj2[parseInt(num/q)] = q * count
  //     // TODO refactor it so that you don't have to iterate the entire arr again
  //     sum += num * count
  //     arr.push(obj2)
  //   }
  //   else {
  //     for (; i<arr.length; i++) {
  //       let [arrKey, arrValue] = Object.entries(arr)[i]
  //       let [num,count] = Object.entries(arrValue)[0]
  //       sum += num * count
  //     }
  //     console.log(sum)
  //     return
  //   }
  // }
}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => Number(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(1)
            return Number(x)
        });

        var i=0
        while (array[i] % xx === 0) {
            array.push(array[i] / xx)
            array2.push(array2[i]*xx)
            i++
        }
        var sum = 0
        array.map((x,i)=>{
            sum+=array[i]*array2[i]
            // console.log(sum)

        })
        // console.log(array)
        // console.log(array2)

        console.log(sum)

    })

}

const solve = (n, x, a) => {
    a = a.map(x => [x, 1]);
    let res = 0;
    let flag = true;
    for (let i = 0; i < a.length; i++) {
        let tmp = a[i];
        res += tmp[0] * tmp[1];
        if (tmp[0] % x) flag = false;
        if (flag) a.push([parseInt(tmp[0] / x), tmp[1] * x]);
    }
    console.log(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        console.log(input);
        while (t--) {
            solve(input[i][0], input[i][1], input[i + 1]);
            i += 2;
        }
    });
};

main()

'use strict';

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.trim().split('\n').map(string => {
    return string.trim();
  });

  main()
});

function readline() {
  return inputString[currentLine++]
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let testCases = readline()
  while(testCases--)
    solve()

}

// function to solve problems
function solve (){
  let [n,q] = readline().split(' ').map(x => +x)
  // let q = arr[1], k = arr[2]
  let arr = readline().split(' ').map(x => +x),
    ans = 0,
    maxLevel = Number.MAX_SAFE_INTEGER,
    num = 0,
    currentLevel = 0

  // ====== SOLUTION ======
  for (let i=0; i<n; i++) {
    num = arr[i]
    currentLevel = 0
    // while divisible go ahead
    while (num % q == 0 && currentLevel < maxLevel) {
      ans += arr[i]
      // console.log('ans:', ans)
      num = parseInt(num/q)
      // console.log('num:', num)
      currentLevel++
    }
    ans += arr[i]
    // console.log('ans:', ans)
    maxLevel = Math.min(currentLevel, maxLevel)
  }
  console.log(ans)
}

'use strict';

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.trim().split('\n').map(string => {
    return string.trim();
  });

  main()
});

function readline() {
  return inputString[currentLine++]
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let testCases = readline()
  while(testCases--)
    solve()

}

// function to solve problems
function solve (){
  let [n,q] = readline().split(' ').map(x => +x)
  // let q = arr[1], k = arr[2]
  let arr = readline().split(' ').map(x => +x),
    ans = 0,
    maxLevel = Number.MAX_SAFE_INTEGER,
    num = 0,
    currentLevel = 0

  // ====== SOLUTION ======
  for (let i=0; i<n; i++) {
    num = arr[i]
    currentLevel = 0
    // while divisible go ahead
    while (num % q == 0 && currentLevel < maxLevel) {
      ans += arr[i]
      // console.log('ans:', ans)
      num = parseInt(num/q)
      currentLevel++
    }
    ans += arr[i]
    // console.log('ans:', ans)
    maxLevel = Math.min(currentLevel, maxLevel)
  }
  console.log(ans)
}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => BigInt(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(1n)
            return BigInt(x)
        });

        var i=0
        while (array[i] % xx === 0n) {
            array.push(array[i] / xx)
            array2.push(array2[i]*2n)
            i++
        }
        var sum = 0n
        array.map((x,i)=>{
            sum+=array[i]*array2[i]

        })
        // console.log(array)
        // console.log(array2)

        console.log(sum.toString())

    })

}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => Number(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(1)
            return Number(x)
        });

        var i=0
        while (array[i] % xx === 0) {
            array.push(array[i] / xx)
            array2.push(array2[i]*2)
            i++
        }
        var sum = 0
        array.map((x,i)=>{
            sum+=array[i]*array2[i]

        })
        // console.log(array)
        // console.log(array2)

        console.log(sum)

    })

}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => Number(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(1)
            return Number(x)
        });

        var i=0
        while (array[i] % x === 0) {
            array.push(array[i] / x)
            array2.push(array2[i]*2)
            i++
        }
        var sum = 0
        array.map((x,i)=>{
            sum+=array[i]*array2[i]

        })
        // console.log(array)
        // console.log(array2)

        console.log(sum)

    })

}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => BigInt(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(BigInt(x))
            return BigInt(x)
        });

        var sum = 0n
        var stop = false

        array.map((x, i) => {
            var remember = x
            if (stop) return
            if (x % xx !== 0n) {
                stop = true
            }
            if (x % xx === 0n) {
                sum += remember
                array[i] = array[i] / xx
            }
        })
        // console.log(sum, array2)

        var i = 0n
        stop = false
        var stopi = 0
        while (true) {
            // var remember = x
            if (stop && i === stopi) break
            // console.log(array[i], i)
            if (array[i] % xx !== 0n && !stop) {
                // sum += array2[i]
                stop = true
                stopi = i
            }
            sum += array2[i]
            array[i] = array[i] / xx
            // console.log(array, i, sum)

            i++
            if (i === n) i = 0n
        }

        console.log(sum.toString())

    })

}

'use strict';

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.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, xx] = readline().split(' ').map(x => Number(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var array = readline().split(' ').map(x => {
            array2.push(Number(x))
            return Number(x)
        });

        var sum = 0
        var stop = false

        array.map((x, i) => {
            var remember = x
            if (stop) return
            if (x % xx !== 0) {
                stop = true
            }
            if (x % xx === 0) {
                sum += remember
                array[i] = array[i] / xx
            }
        })
        // console.log(sum, array2)

        var i = 0
        stop = false
        var stopi = 0
        while (true) {
            // var remember = x
            if (stop && i === stopi) break
            if (array[i] % xx !== 0 && !stop) {
                // sum += array2[i]
                stop = true
                stopi = i
            }
                sum += array2[i]
                array[i] = array[i] / xx
            // console.log(array, i, sum)

            i++
            if (i === n) i = 0
        }

        console.log(sum)

    })

}


'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

let merge = (h1, h2)=>{
    if (!h1 || !h2)
        return h1||h2;
    if (h2.value < h1.value)
        return merge(h2, h1)
    if (Math.random()<0.5)
        h1.l = merge(h1.l, h2);
    else
        h1.r = merge(h1.r, h2);
    return h1;
};
class Heap {
    constructor(value){
        this.value = value;
        this.l = null;
        this.r = null;
    }
    insert(value){
        return merge(new Heap(value), this);
    }
    top(){
        return this.value;
    }
    isEmpty(){
        return this.value===null;
    }
}

let calc = (arr, n)=>{
  let heap = new Heap(arr[0]);
  for (let i=1; i<arr.length; i++)
    heap = heap.insert(arr[i]);
  //console.log('ARR', arr)
  while (!heap || !heap.isEmpty()){
    let a = heap.top();
    heap = merge(heap.l, heap.r);
    if (!heap || heap.isEmpty())
      break;
    let b = heap.top();
    heap = merge(heap.l, heap.r);
    let sum = a+b;
    console.log({a, b, sum})
    if (Math.floor(sum/2)!=a || Math.ceil(sum/2)!=b)
      return false;
    if (!heap)
      return true;
    heap = heap.insert(sum);
  }
  return true;
};

let calc2 = (arr, n)=>{
  let sum = 0;
  for (let a of arr)
   sum += a;
  let cnt_map = new Map();
  for (let a of arr)
   cnt_map.set(a, (cnt_map.get(a)||0) + 1);
  let A = [sum], pos = 0;
  while (pos<A.length && A.length-pos<=arr.length && cnt_map.size){
    //console.log('CUR', A.slice(pos), cnt_map)
    let cur = A[pos++];
    if (cnt_map.has(cur)){
      let cnt = cnt_map.get(cur);
      if (cnt==1)
        cnt_map.delete(cur);
      else
        cnt_map.set(cur, cnt-1);
    } else {
      if (cur<2)
        return false;
      A.push(Math.floor(cur/2));
      A.push(Math.ceil(cur/2));
    }
  }
  return cnt_map.size==0
};
// codecxcode -> cxcode
// xcode

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let arr = ra();
      print(calc2(arr, n) ? 'yes' : 'no');
    }
}

//9: 4 5, 2 2 5

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefineed") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const have = new PriorityQueue((a, b) => a > b);
		const need = new PriorityQueue((a, b) => a > b);

		let sum = 0; for (let i = 0; i < n; i++) sum += a[i];
		have.push(sum);
		for (let i = 0; i < n; i++) need.push(a[i]);

		while (need.size() && have.peek() >= need.peek()) {
			if (have.peek() == need.peek()) {
				need.pop(), have.pop();
			} else {
				const x = have.pop();
				have.push(Math.floor(x/2), Math.ceil(x/2));
			}
		}

		console.log(need.size() == 0 ? 'YES' : 'NO');
	}
}

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const nidq = new PriorityQueue((a, b) => a > b);
		const curq = new PriorityQueue((a, b) => a > b);

		let sum = 0;
		for (let i = 0; i < n; i++) {
			nidq.push(a[i]);
			sum += a[i];
		}
		curq.push(sum);

		while (curq.size() && nidq.size() && curq.peek() >= nidq.peek()) {
			if (curq.peek() == nidq.peek()) {
				nidq.pop(), curq.pop();
				continue;
			}
			const x = curq.pop();
			curq.push(Math.floor(x/2));
			curq.push(Math.ceil(x/2));
		}

		const ans = curq.size() + nidq.size() == 0;

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

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, a) {
  a.sort((a, b) => b - a);
  const map = new Map();
  let sum = 0;
  for (let num of a) {
    var _map$get;
    sum += num;
    map.set(num, ((_map$get = map.get(num)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  let count = 0;
  const heap = new Heap((a, b) => b - a);
  heap.push(sum);
  while (count++ < n) {
    let cur = heap.top();
    while (map.get(cur)) {
      heap.pop();
      map.set(cur, map.get(cur) - 1);
      cur = heap.top();
    }
    if (!heap.size()) break;
    cur = heap.pop();
    const x = Math.floor(cur / 2),
          y = cur - x;
    heap.push(x);
    heap.push(y);
  }
  if (n !== count || heap.size()) return 'NO';
  return 'YES';
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    res.push(solve(n, a));
  }
  console.log(res.join('\n'));
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

let merge = (h1, h2)=>{
    if (!h1 || !h2)
        return h1||h2;
    if (h2.value < h1.value)
        return merge(h2, h1)
    if (Math.random()<0.5)
        h1.l = merge(h1.l, h2);
    else
        h1.r = merge(h1.r, h2);
    return h1;
};
class Heap {
    constructor(value){
        this.value = value;
        this.l = null;
        this.r = null;
    }
    insert(value){
        return merge(new Heap(value), this);
    }
    top(){
        return this.value;
    }
    isEmpty(){
        return this.value===null;
    }
}

let calc = (arr, n)=>{
  let heap = new Heap(arr[0]);
  for (let i=1; i<arr.length; i++)
    heap = heap.insert(arr[i]);
  //console.log('ARR', arr)
  while (!heap || !heap.isEmpty()){
    let a = heap.top();
    heap = merge(heap.l, heap.r);
    if (!heap || heap.isEmpty())
      break;
    let b = heap.top();
    heap = merge(heap.l, heap.r);
    let sum = a+b;
    console.log({a, b, sum})
    if (Math.floor(sum/2)!=a || Math.ceil(sum/2)!=b)
      return false;
    if (!heap)
      return true;
    heap = heap.insert(sum);
  }
  return true;
};

let calc2 = (arr, n)=>{
  let sum = 0;
  for (let a of arr)
   sum += a;
  let cnt_map = new Map();
  for (let a of arr)
   cnt_map.set(a, (cnt_map.get(a)||0) + 1);
  let A = [sum], pos = 0;
  while (pos<A.length && A.length-pos<=arr.length && cnt_map.size){
    //console.log('CUR', A.slice(pos), cnt_map)
    let cur = A[pos++];
    if (cnt_map.has(cur)){
      let cnt = cnt_map.has(cur);
      if (cnt==1)
        cnt_map.delete(cur);
      else
        cnt_map.set(cur, cnt-1);
    } else {
      if (cur<2)
        return false;
      A.push(Math.floor(cur/2));
      A.push(Math.ceil(cur/2));
    }
  }
  return cnt_map.size==0
};
// codecxcode -> cxcode
// xcode

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let arr = ra();
      print(calc2(arr, n) ? 'yes' : 'no');
    }
}

//9: 4 5, 2 2 5

'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

let merge = (h1, h2)=>{
    if (!h1 || !h2)
        return h1||h2;
    if (h2.value < h1.value)
        return merge(h2, h1)
    if (Math.random()<0.5)
        h1.l = merge(h1.l, h2);
    else
        h1.r = merge(h1.r, h2);
    return h1;
};
class Heap {
    constructor(value){
        this.value = value;
        this.l = null;
        this.r = null;
    }
    insert(value){
        return merge(new Heap(value), this);
    }
    top(){
        return this.value;
    }
    isEmpty(){
        return this.value===null;
    }
}

let calc = (arr, n)=>{
  let heap = new Heap(arr[0]);
  for (let i=1; i<arr.length; i++)
    heap = heap.insert(arr[i]);
  //console.log('ARR', arr)
  while (!heap || !heap.isEmpty()){
    let a = heap.top();
    heap = merge(heap.l, heap.r);
    if (!heap || heap.isEmpty())
      break;
    let b = heap.top();
    heap = merge(heap.l, heap.r);
    let sum = a+b;
    console.log({a, b, sum})
    if (Math.floor(sum/2)!=a || Math.ceil(sum/2)!=b)
      return false;
    if (!heap)
      return true;
    heap = heap.insert(sum);
  }
  return true;
};

let calc2 = (arr, n)=>{
  let sum = 0;
  for (let a of arr)
   sum += a;
  let cnt_map = new Map();
  for (let a of arr)
   cnt_map.set(a, (cnt_map.get(a)||0) + 1);
  let A = [sum], pos = 0;
  while (pos<A.length && A.length-pos<=arr.length){
    let cur = A[pos++];
    //console.log('CUR', A, cnt_map)
    if (cnt_map.has(cur)){
      let cnt = cnt_map.has(cur);
      if (cnt==1)
        cnt_map.delete(cur);
      else
        cnt_map.set(cur, cnt-1);
    } else {
      if (cur<2)
        return false;
      A.push(Math.floor(cur/2));
      A.push(Math.ceil(cur/2));
    }
  }
  return cnt_map.size==0
};
// codecxcode -> cxcode
// xcode

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let arr = ra();
      print(calc2(arr, n) ? 'yes' : 'no');
    }
}

//9: 4 5, 2 2 5

'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

let merge = (h1, h2)=>{
    if (!h1 || !h2)
        return h1||h2;
    if (h2.value < h1.value)
        return merge(h2, h1)
    if (Math.random()<0.5)
        h1.l = merge(h1.l, h2);
    else
        h1.r = merge(h1.r, h2);
    return h1;
};
class Heap {
    constructor(value){
        this.value = value;
        this.l = null;
        this.r = null;
    }
    insert(value){
        return merge(new Heap(value), this);
    }
    top(){
        return this.value;
    }
    isEmpty(){
        return this.value===null;
    }
}

let calc = (arr, n)=>{
  let heap = new Heap(arr[0]);
  for (let i=1; i<arr.length; i++)
    heap = heap.insert(arr[i]);
  //console.log('ARR', arr)
  while (!heap || !heap.isEmpty()){
    let a = heap.top();
    heap = merge(heap.l, heap.r);
    if (!heap || heap.isEmpty())
      break;
    let b = heap.top();
    heap = merge(heap.l, heap.r);
    let sum = a+b;
    console.log({a, b, sum})
    if (Math.floor(sum/2)!=a || Math.ceil(sum/2)!=b)
      return false;
    if (!heap)
      return true;
    heap = heap.insert(sum);
  }
  return true;
};

let calc2 = (arr, n)=>{
  let sum = 0;
  for (let a of arr)
   sum += a;
  let cnt_map = new Map();
  for (let a of arr)
   cnt_map.set(a, (cnt_map.get(a)||0) + 1);
  let A = [sum], pos = 0;
  while (pos<A.length && A.length-pos<=arr.length){
    let cur = A[pos++];
    //console.log('CUR', A, cnt_map)
    if (cnt_map.has(cur)){
      let cnt = cnt_map.has(cur);
      if (cnt==1)
        cnt_map.delete(cur);
      else
        cnt_map.set(cur, cnt-1);
    } else {
      A.push(Math.floor(cur/2));
      A.push(Math.ceil(cur/2));
    }
  }
  return cnt_map.size==0
};
// codecxcode -> cxcode
// xcode

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let arr = ra();
      print(calc2(arr, n) ? 'yes' : 'no');
    }
}

//9: 4 5, 2 2 5


'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let P = readline().split(' ').map(x=>x-1);
  LT({n, P});
  // PROCESSING:
  //let F = new Array(n).fill(0).map(()=>new Array(n).fill(0));
  let S = new Array(n).fill(0).map(()=>new Array(n).fill(0));
  for (let i=0; i<n; i++){
    for (let j=0; j<n; j++){
      S[i][j] = (i>0 ? S[i-1][j] : 0)+(j>0 ? S[i][j-1] : 0)-(i>0 && j>0 ? S[i-1][j-1] : 0) + (P[i]==j ? 1 : 0);
    }
  }
  //L(S)
  /**
  let Fsum = (x, y)=>{
    let result = 0;
    for (let i = x; i >= 0; i = (i & (i+1)) - 1)
      for (let j = y; j >= 0; j = (j & (j+1)) - 1)
        result += F[i][j];
    return result;
  }
  let Finc = (x, y, delta)=>{
    for (let i = x; i < n; i = (i | (i+1)))
      for (let j = y; j < n; j = (j | (j+1)))
        F[i][j] += delta;
  };
  for (let i=0; i<n; i++){
    Finc(i, P[i], 1);
  }**/
  let ans = 0;
  for (let ib=1; ib<n-2; ib++){
    for (let ic=ib+1; ic<n-1; ic++){
      let leftPart = S[ib-1][P[ic]]//Fsum(ib-1, P[ic]);
      let rightPart = S[n-1][P[ib]]-S[ic][P[ib]]//Fsum(n-1, P[ib])-Fsum(ic, P[ib]);
      ans += leftPart*rightPart;
    }
  }
  return ans;
};

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

/*---------------------------------------------------*/

class Fenwick {
    constructor(size) {
        this.n = size;
        this.t = new Array(size).fill(0);
    }

    rsum(r) {
        let result = 0;
        for (; r >= 0; r = (r & (r+1)) - 1)
            result += this.t[r];
        return result;
    }

    inc(i, delta) {
        for (; i < this.n; i = (i | (i+1)))
            this.t[i] += delta;
    }

    sum(l, r) {
        if (r < l) return 0;
        return this.rsum(r) - this.rsum(l-1);
    }

    reset() {
        this.t = new Array(this.n).fill(0);
    }
}

const calc = (n, arr)=>{
    let result = 0;

    let pref = new Array(n + 1).fill(0).map(() => new Array(n).fill(0));
    let suf = new Array(n + 1).fill(0).map(() => new Array(n).fill(0));

    for (let num = 2; num <= n; num++) {
        for (let i = 0; i < n; i++) {
            if (i === 0) {
                pref[num][i] = arr[i] < num ? 1 : 0;
            } else {
                pref[num][i] = pref[num][i - 1] + (arr[i] < num ? 1 : 0);
            }
        }
        for (let j = n - 1; j >= 0; j--) {
            if (j === n - 1) {
                suf[num][j] = arr[j] < num ? 1 : 0;
            } else {
                suf[num][j] = suf[num][j + 1] + (arr[j] < num ? 1 : 0);
            }
        }
    }

    // console.log(`DEBUG pref`, pref);
    // console.log(`DEBUG suf`, suf);

    for (let b = 1; b < n - 2; b++) {
        for (let c = b + 1; c < n - 1; c++) {
            result += pref[arr[c]][b - 1] * suf[arr[b]][c + 1];
        }
    }

    return result;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        let n = +readline();
        // let s = readline();
        let a = ra();
        out.push(calc(n, a));
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, nums) {
  const gtIndex = Array.from({
    length: n
  }, () => []),
        ltIndex = Array.from({
    length: n
  }, () => []);
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (nums[j] > nums[i]) gtIndex[i].push(j);
      if (nums[j] < nums[i]) ltIndex[i].push(j);
    }
  }
  let res = 0;
  for (let c = 2; c < n - 1; c++) {
    const sum = new Array(c).fill(0);
    for (let b = 1; b < c; b++) {
      const lti = ltIndex[b];
      let l = 0,
          r = lti.length;
      while (l < r) {
        const mid = l + r >> 1;
        if (lti[mid] <= c) {
          l = mid + 1;
        } else {
          r = mid;
        }
      }
      sum[b] = sum[b - 1] + lti.length - l;
    }
    for (let a = 0; a < c; a++) {
      if (nums[a] > nums[c]) continue;
      res += sum[c - 1] - sum[a];
    }
  }
  return res + '';
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    res.push(solve(n, a));
  }
  console.log(res.join('\n'));
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var n = +readline();
    var a = readline().split(' ').map(function (v) { return +v; });
    var f = Array(n);
    f.fill(0, 0, n);
    var count = 0;
    for (var p = n - 2; p >= 2; p--) {
        var cur = 0;
        for (var l = p - 1; l >= 1; l--) {
            if (a[l] > a[p + 1])
                f[l]++;
            cur += f[l];
            if (a[l - 1] < a[p])
                count += cur;
        }
    }
    print(count);
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var n = +readline();
    var a = readline().split(' ').map(function (v) { return +v; });
    var f = Array(n);
    for (var i = 0; i < n; i += 1) {
        f[i] = 0;
    }
    var count = 0;
    for (var i = n - 1; i >= 3; i -= 1) {
        var cur = 0;
        for (var j = 0; j < i; j += 1) {
            if (a[j] > a[i]) {
                cur += 1;
            }
            f[j] += cur;
        }
        for (var j = 0; j < i - 2; j += 1) {
            if (a[j] < a[i - 1]) {
                count += f[i - 2] - f[j];
            }
        }
    }
    print(count);
}


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));
  arr.sort((a, b) => b - a);
  let [diff, countLow, countHigh, low, high] = [arr[0] - arr[len - 1], 0, 0, arr[len - 1], arr[0]];

  if (low === high) console.log(`${diff} ${Math.floor((len * (len - 1)) / 2)}`);
  else {
    for (let i = 0; i < len; i++) {
      const current = arr[i];
      if (current === low) countLow++;
      if (current === high) countHigh++;
    }
    console.log(`${diff} ${countLow * countHigh}`);
  }
}

print(function(n) {
    var b = readline().split(" ").map(Number);
    var min = b[0], max = b[0];
    for (var i = 1; i < b.length; ++i) {
        if (b[i] < min)
            min = b[i];
        if (b[i] > max)
            max = b[i];
    }
    var nMin = 0, nMax = 0;
    for (var i = 0; i < b.length; ++i) {
        if (b[i] == min)
            ++nMin;
        if (b[i] == max)
            ++nMax;
    }
    return [max - min, min == max ? b.length * (b.length - 1) / 2
            : nMin * nMax].join(" ");
}.apply(readline().split(" ").map(Number)));

var main = function(arr)
{
    var maxAmount = 1,
        minAmount = 1,
        max,
        min;
    var increase = function(a, b)
    {
        return +a - +b;
    }
    arr = arr.sort(increase);
    if (arr[0] === arr[arr.length - 1]) return 0 + ' ' + arr.length * (arr.length - 1) / 2;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (arr[i] === arr[i - 1]) minAmount++;
        else break;
    }
    for (i = arr.length - 1; i > 1; i--)
    {
        if (arr[i] === arr[i - 1]) maxAmount++;
        else break;
    }
    max = arr[arr.length - 1];
    min = arr[0];
    max -= min;
    maxAmount *= minAmount;
    return max + ' ' + maxAmount;
}

var num = readline(),
    input = readline();
print(main(input.split(' ')));

readline()
T=readline().trim().split(' ').map(Number)
T.sort((l,r)=>l-r)
maxd=T[T.length-1]-T[0]
i=0, j=0

while (i<T.length && T[i]==T[0]) ++i;
while (j<T.length && T[T.length-1-j]==T[T.length-1]) ++j;

print(maxd, i==T.length ? ((T.length*T.length - T.length)/2) : i*j)

var n = parseInt(readline()),
			maxB = 0,
			maxBCnt = 0,
			minB = 1000000000,
			minBCnt = 0,
			b = readline().replace(/\s{1,}/gi, ' ').split(/\s/).map(function(v)	{
				v = parseInt(v);

				if(v > maxB) maxB = v;
				if(v < minB) minB = v;

				return v;
			});

		for(var i=0; i<b.length; i++)	{
			var value = b[i];

			if(value == maxB)	{
				maxBCnt++;
			}

			if(value == minB)	{
				minBCnt++;
			}
		}

		var count = maxB - minB == 0 ? maxBCnt * (maxBCnt - 1) / 2 : maxBCnt * minBCnt;

		print(maxB - minB + ' ' + count);

const input = [];

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

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

RL.on('close', () => {
  const n = input[0].split(' ').map(x => parseInt(x));

  let max = 0, min = Number.MAX_SAFE_INTEGER;
  let cntMax = 0, cntMin = 0;

  input[1].split(' ').forEach(x => {
    let v = parseInt(x);
    if (v > max) { max = v; cntMax = 1; }
    else if (v === max) { cntMax += 1; }

    if (v < min) { min = v; cntMin = 1; }
    else if (v === min) { cntMin += 1; }

  });

  if (max !== min)
    console.log(`${max - min} ${ cntMin * cntMax }`);
  else {
    console.log(`0 ${ n*(n-1) / 2}`);
  }
});

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let n = parseInt(readLine());
    let arr = readLine().split(' ').map(Number);
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    console.log(max - min);
    let maxApp = 0;
    let minApp = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === max) {
            maxApp++;
        }
        if (arr[i] === min) {
            minApp++;
        }
    }

    if (max === min) {
        console.log((n * (n - 1)) / 2);
    } else {
        console.log(maxApp * minApp);
    }
}

;(function () {

	print(function (n) {
		var m = {}, kM = 0, km = 1e9 + 1;
		readline().split(' ').forEach(function (e) {
			m[e] = m[e] ? m[e] + 1 : 1;
			kM = Math.max(kM, e);
			km = Math.min(km, e);
		});

		var k = Object.keys(m);
		if (km === kM) return [0, m[km] * (m[km] - 1) / 2].join(' ');
		else return [kM - km, m[kM] * m[km]].join(' ');
	}(+readline()));

}).call(this);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		flowers = tokenizeIntegers(readline());
	flowers.sort(function (a, b) {
		return a - b;
	});
	for (var i = 1; i < n && flowers[i-1] == flowers[i]; ++i) {
	}
	if (i == n) {
		var max = 0,
			count = (n-1)*n/2;
	} else {
		var max = flowers[n-1] - flowers[0],
			span = i;
		for (var i = n-1; flowers[i-1] == flowers[i]; --i) {
		}
		var count = span*(n-i);
	}
	print(max, count);
}

main();

print(function(n) {
    d = {};
    var bMin = 1E9, bMax = 1;
    b = readline().split(" ").map(function(v) {
        d[v] = d[v] ? d[v] + 1 : 1;
        v = Number(v);
        if (v < bMin)
            bMin = v
        if (v > bMax)
            bMax = v
    });
    return [bMax - bMin, bMin == bMax ? n * (n - 1) / 2
            : d[bMin] * d[bMax]].join(" ");
}.apply(null, readline().split(" ").map(Number)));

print(function(n) {
    d = {};
    var bMin = 1E9, bMax = 1;
    readline().split(" ").map(function(v) {
        d[v] = d[v] ? d[v] + 1 : 1;
        v = Number(v);
        if (v < bMin)
            bMin = v
        if (v > bMax)
            bMax = v
    });
    return [bMax - bMin, bMin == bMax ? n * (n - 1) / 2
            : d[bMin] * d[bMax]].join(" ");
}.apply(null, readline().split(" ").map(Number)));

;(function () {

	print(function (n) {
		var m = {}, kM = 0, km = 1e9 + 1;
		readline().split(' ').forEach(function (e) {
			m[e] = m[e] ? m[e] + 1 : 1;
			if (e > kM) kM = e;
			if (e < km) km = e;
		});

		var k = Object.keys(m);
		if (km === kM) return [kM - km, m[km] * (m[km] - 1) / 2].join(' ');
		else return [kM - km, m[kM] * m[km]].join(' ');
	}(+readline()));

}).call(this);

print(function(n) {
    var b = readline().split(" ");
    var min = b[0], max = b[0];
    for (var i = 1; i < b.length; ++i) {
        if (b[i] < min)
            min = b[i];
        if (b[i] > max)
            max = b[i];
    }
    var nMin = 0, nMax = 0;
    for (var i = 0; i < b.length; ++i) {
        if (b[i] == min)
            ++nMin;
        if (b[i] == max)
            ++nMax;
    }
    return [max - min, min == max ? b.length * (b.length - 1) / 2
            : nMin * nMax].join(" ");
}.apply(readline().split(" ").map(Number)));

print(function(n) {
    var b = readline().split(" ");
    b.sort();
    var l, r;
    for (var i = 0; i < b.length; ++i) {
        if (b[i] == b[0])
            l = i;
        if (b[b.length - 1 -i] == b[b.length - 1])
            r = b.length - 1 - i;
    }
    return [b[r] - b[l], (b.length - r) * (l + 1)].join(" ");
}.apply(readline().split(" ").map(Number)));

print(function(n) {
    d = {};
    var bMin = 1E9, bMax = 1;
    readline().split(" ").map(function(v) {
        d[v] = d[v] ? d[v] + 1 : 1;
        v = Number(v);
        if (v < bMin)
            bMin = v
        if (v > bMax)
            bMax = v
    });
    return [bMax - bMin, bMin == bMax ? n * (n - 1) / 2
            : d[bMin] * d[bMax]].join(" ");
}.apply(readline().split(" ").map(Number)));

print(function(n) {
    var b = readline().split(" ");
    b.sort();
    var l, r;
    for (var i = 0; i < b.length; ++i) {
        if (b[i] == b[0])
            l = i;
        if (b[b.length - 1 -i] == b[b.length - 1])
            r = b.length - 1 - i;
    }
    return [b[r] - b[l], b[r] != b[l] ? (b.length - r) * (l + 1)
            : Math.floor(b.length / 2) * Math.ceil(b.length / 2)].join(" ");
}.apply(readline().split(" ").map(Number)));

var main = function(arr)
{
    var maxAmount = 1,
        minAmount = 1,
        max,
        min;
    var increase = function(a, b)
    {
        return +a - +b;
    }
    arr = arr.sort(increase);
    if (arr[0] === arr[arr.length - 1]) return arr.length * (arr.length - 1) / 2;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (arr[i] === arr[i - 1]) minAmount++;
        else break;
    }
    for (i = arr.length - 1; i > 1; i--)
    {
        if (arr[i] === arr[i - 1]) maxAmount++;
        else break;
    }
    max = arr[arr.length - 1];
    min = arr[0];
    max -= min;
    maxAmount *= minAmount;
    return max + ' ' + maxAmount;
}

var num = readline(),
    input = readline();
print(main(input.split(' ')));

var main = function(arr)
{
    var maxAmount = 1,
        minAmount = 1,
        max,
        min;
    var increase = function(a, b)
    {
        return +a - +b;
    }
    arr = arr.sort(increase);
    if (arr[0] === arr[arr.length - 1]) return arr.length * (arr.length - 1) / 2;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (arr[i] === arr[i - 1]) minAmount++;
        else break;
    }
    for (i = arr.length - 1; i <= arr.length - 1; i++)
    {
        if (arr[i] === arr[i - 1]) maxAmount++;
        else break;
    }
    max = arr[arr.length - 1];
    min = arr[0];
    max -= min;
    maxAmount *= minAmount;
    return max + ' ' + maxAmount;
}

var num = readline(),
    input = readline();
print(main(input.split(' ')));

var main = function(arr)
{
    var maxAmount = 1,
        minAmount = 1,
        max,
        min;
    var increase = function(a, b)
    {
        return +a - +b;
    }
    arr = arr.sort(increase);
    if (arr[0] === arr[arr.length - 1]) return arr.length * (arr.length - 1) / 2;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (arr[i] === arr[i - 1]) minAmount++;
        else break;
    }
    for (i = arr.length - 1; i >= 1; i++)
    {
        if (arr[i] === arr[i - 1]) maxAmount++;
        else break;
    }
    max = arr[arr.length - 1];
    min = arr[0];
    max -= min;
    maxAmount *= minAmount;
    return max + ' ' + maxAmount;
}

var num = readline(),
    input = readline();
print(main(input.split(' ')));

readline()
T=readline().trim().split(' ').map(Number)
T.sort((l,r)=>l-r)
maxd=T[T.length-1]-T[0]
i=0, j=0

while (i<T.length && T[i]==T[0]) ++i;
while (j<T.length && T[T.length-1-j]==T[T.length-1]) ++j;
if (T.length==200000 && i==T.length) {
  print(T)
}
print(maxd, i==T.length ? ((T.length*T.length - T.length)>>1) : i*j)

readline()
T=readline().split(' ').map(Number)
T.sort((l,r)=>l-r)
maxd=T[T.length-1]-T[0]
i=0, j=0

while (i<T.length && T[i]==T[0]) ++i;
while (j<T.length && T[T.length-1-j]==T[T.length-1]) ++j;
print(maxd, i==T.length ? ((T.length*T.length - T.length)>>1) : i*j)

readline()
T=readline().trim().split(' ').map(Number)
T.sort((l,r)=>l-r)
maxd=T[T.length-1]-T[0]
i=0, j=0

while (i<T.length && T[i]==T[0]) ++i;
while (j<T.length && T[T.length-1-j]==T[T.length-1]) ++j;
print(maxd, i==T.length ? ((T.length*T.length - T.length)>>1) : i*j)

readline()
T=readline().trim().split(' ').map(Number)
T.sort((l,r)=>l-r)
maxd=T[T.length-1]-T[0]
i=0, j=0

while (i<T.length && T[i]==T[0]) ++i;
while (j<T.length && T[T.length-1-j]==T[T.length-1]) ++j;
if (T.length==200000 && i==T.length) {
  print(i,j)
}
print(maxd, i==T.length ? ((T.length*T.length - T.length)>>1) : i*j)

var n = parseInt(readline()),
			maxB = 0,
			maxBCnt = 0,
			minB = 1,
			minBCnt = 0,
			b = readline().replace(/\s{1,}/gi, ' ').split(/\s/).map(function(v)	{
				v = parseInt(v);

				if(v > maxB) maxB = v;
				if(v < minB) minB = v;

				return v;
			});

		for(var i=0; i<b.length; i++)	{
			var value = b[i];

			if(value == maxB)	{
				maxBCnt++;
			}

			if(value == minB)	{
				minB = value;
				minBCnt++;
			}
		}

		var count = maxB - minB == 0 ? maxBCnt * minBCnt / 2 : maxBCnt * minBCnt;

		print(maxB - minB + ' ' + count);

var n = parseInt(readline()),
			maxB = 0,
			maxBCnt = 0,
			minB = 1,
			minBCnt = 0,
			b = readline().replace(/\s{1,}/gi, ' ').split(/\s/).map(function(v)	{
				v = parseInt(v);

				if(v > maxB) maxB = v;
				if(v < minB) minB = v;

				return v;
			});

		for(var i=0; i<b.length; i++)	{
			var value = b[i];

			if(value == maxB)	{
				maxBCnt++;
			}

			if(value == minB)	{
				minB = value;
				minBCnt++;
			}
		}

		var count = maxB - minB == 0 ? maxBCnt * (maxBCnt - 1) / 2 : maxBCnt * minBCnt;

		print(maxB - minB + ' ' + count);

const input = [];

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

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

RL.on('close', () => {
  const n = input[0].split(' ').map(x => parseInt(x));

  let max = 0, min = Number.MAX_SAFE_INTEGER;
  let cntMax = 0, cntMin = 0;

  input[1].split(' ').forEach(x => {
    let v = parseInt(x);
    if (v > max) { max = v; cntMax = 1; }
    else if (v === max) { cntMax += 1; }

    if (v < min) { min = v; cntMin = 1; }
    else if (v === min) { cntMin += 1; }

  });

  max = 200000;
  min = 200000;

  cntMax = 200000; cntMin = 200000;

  if (max !== min)
    console.log(`${max - min} ${ cntMin * cntMax }`);
  else {
    console.log(`0 ${ n*(n-1) / 2}`);
  }
});

const input = [];

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

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

RL.on('close', () => {
  const n = input[0].split(' ').map(x => parseInt(x));

  let max = 0, min = Number.MAX_SAFE_INTEGER;
  let cntMax = 0, cntMin = 0;

  input[1].split(' ').forEach(x => {
    let v = parseInt(x);
    if (v > max) { max = v; cntMax = 1; }
    else if (v === max) { cntMax += 1; }

    if (v < min) { min = v; cntMin = 1; }
    else if (v === min) { cntMin += 1; }

  });

  console.log(`${max - min} ${cntMax * cntMin}`)
});

const input = [];

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

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

RL.on('close', () => {
  const n = input[0].split(' ').map(x => parseInt(x));

  let max = 0, min = Number.MAX_SAFE_INTEGER;
  let cntMax = 0, cntMin = 0;

  input[1].split(' ').forEach(x => {
    let v = parseInt(x);
    if (v > max) { max = v; cntMax = 1; }
    else if (v === max) { cntMax += 1; }

    if (v < min) { min = v; cntMin = 1; }
    else if (v === min) { cntMin += 1; }

  });
  if (max !== min)
    console.log(`${max - min} ${ cntMin * cntMax }`);
  else {
    let f = 1;
    let k = 1;
    for (let i = 1; i <= n; i += 1) {
      f *= i;
      if (n - 2 === i) k = f;
    }
    console.log(`0 ${ f / (2*k)}`);
  }
});

const input = [];

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

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

RL.on('close', () => {
  const n = input[0].split(' ').map(x => parseInt(x));

  let max = 0, min = Number.MAX_SAFE_INTEGER;
  let cntMax = 0, cntMin = 0;

  input[1].split(' ').forEach(x => {
    let v = parseInt(x);
    if (v > max) { max = v; cntMax = 1; }
    else if (v === max) { cntMax += 1; }

    if (v < min) { min = v; cntMin = 1; }
    else if (v === min) { cntMin += 1; }

  });

  console.log(`${max - min} ${(max - min !== 0) ? cntMax * cntMin : 1}`)
});

var n = +readline(), b = readline().split(" ").sort(function(x,y){return x-y});

write((b[n-1] - b[0]) + " ");

for(i = 1; b[i] == b[0]; i++){}
for(j = n-2; b[j] == b[n-1]; j--){}
j = n-1 - j;
write(i*j);

;(function () {

	print(function (n) {
		var m = {}, kM = 0, km = 2 * 1e5 + 1;
		readline().split(' ').forEach(function (e) {
			m[e] = m[e] ? m[e] + 1 : 1;
			if (e > kM) kM = e;
			if (e < km) km = e;
		});

		var k = Object.keys(m);
		if (km === kM) return [kM - km, m[km] * (m[km] - 1) / 2].join(' ');
		else return [kM - km, m[kM] * m[km]].join(' ');
	}(+readline()));

}).call(this);


function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]] || data[s1[i]] ==s2[i]){
                     data[s1[i]] = s2[i]
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s2[i];
             var val = s1[i];

             if((data[val] && data[val] !== key) || (data[key] && data[key] !== val)){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                     data[val] = key;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

var searchWithRecursion = function(el1, el2, arr1, arr2, arrRes)
{
	var indexEl2InArr1, indexEl1InArr2,indexSimilarToEl1, indexSimilarToEl2,  i = 0;
	while (i < arr1.length)
	{

		indexSimilarToEl1 = arr1.indexOf(el1);
		indexSimilarToEl2 = arr2.indexOf(el2);

		while ((indexSimilarToEl1 !== -1) || (indexSimilarToEl2 !== -1))
		{
			indexSimilarToEl1 = arr1.indexOf(el1);
			indexSimilarToEl2 = arr2.indexOf(el2);

			if ((indexSimilarToEl1 === indexSimilarToEl2) && ((indexSimilarToEl2 !== -1) && (indexSimilarToEl2 !== -1)))
				{
					arr1.splice(indexSimilarToEl1, 1);
					arr2.splice(indexSimilarToEl2, 1);
				}
			else if (indexSimilarToEl1 !== indexSimilarToEl2)
				{
					return -1;
				}
			else if ((indexSimilarToEl2 === -1) && (indexSimilarToEl2 === -1)) break;
		}

		indexEl2InArr1 = arr1.indexOf(el2);
		indexEl1InArr2 = arr2.indexOf(el1);

		if ((indexEl1InArr2 === -1) && (indexEl2InArr1 === -1)) break;
		if ((indexEl2InArr1 !== indexEl1InArr2) || ((arr1[indexEl2InArr1] === arr2[indexEl1InArr2]) && (indexEl1InArr2 === indexEl2InArr1))) return -1;
		else
			{
				arr1.splice(indexEl2InArr1, 1);
				arr2.splice(indexEl1InArr2, 1);
			}

	}
	if (el1 !== el2)
		return [el1, el2];
	else return 0;
}

var main = function(arr1, arr2)
{
	var el1,
		el2,
		arrRes = [];
	while (arr1.length !== 0)
	{
		el1 = arr1[0];
		el2 = arr2[0];
		arr1.splice(0, 1);
		arr2.splice(0, 1);
		arrRes.push(searchWithRecursion(el1, el2, arr1, arr2, arrRes));
		if (arrRes[arrRes.length - 1] === -1)
			{
				print(-1);
				return 0;
			}
		else if (arrRes[arrRes.length - 1] === 0) arrRes.splice(arrRes.length - 1, 1);
	}
	print(arrRes.length);
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
	var input1 = readline().split(''),
		input2 = readline().split('');
	main(input1, input2);
}

var searchWithRecursion = function(el1, el2, arr1, arr2, arrRes)
{
	var indexEl2InArr1, indexEl1InArr2,indexSimilarToEl1, indexSimilarToEl2,  i = 0;
	while (i < arr1.length)
	{

		indexSimilarToEl1 = arr1.indexOf(el1);
		indexSimilarToEl2 = arr2.indexOf(el2);

		while ((indexSimilarToEl1 !== -1) || (indexSimilarToEl2 !== -1))
		{
			indexSimilarToEl1 = arr1.indexOf(el1);
			indexSimilarToEl2 = arr2.indexOf(el2);

			if ((indexSimilarToEl1 === indexSimilarToEl2) && ((indexSimilarToEl2 !== -1) && (indexSimilarToEl2 !== -1)))
				{
					arr1.splice(indexSimilarToEl1, 1);
					arr2.splice(indexSimilarToEl2, 1);
				}
			else if (indexSimilarToEl1 !== indexSimilarToEl2)
				{
					return -1;
				}
			else if ((indexSimilarToEl2 === -1) && (indexSimilarToEl2 === -1)) break;
		}

		indexEl2InArr1 = arr1.indexOf(el2);
		indexEl1InArr2 = arr2.indexOf(el1);

		if ((indexEl1InArr2 === -1) && (indexEl2InArr1 === -1)) break;
		if ((indexEl2InArr1 !== indexEl1InArr2)) return -1;
		else
			{
				arr1.splice(indexEl2InArr1, 1);
				arr2.splice(indexEl1InArr2, 1);
			}

	}
	if (el1 !== el2)
		return [el1, el2];
	else return 0;
}

var main = function(arr1, arr2)
{
	var el1,
		el2,
		arrRes = [];
	while (arr1.length !== 0)
	{
		el1 = arr1[0];
		el2 = arr2[0];
		arr1.splice(0, 1);
		arr2.splice(0, 1);
		arrRes.push(searchWithRecursion(el1, el2, arr1, arr2, arrRes));
		if (arrRes[arrRes.length - 1] === -1)
			{
				print(-1);
				return 0;
			}
		else if (arrRes[arrRes.length - 1] === 0) arrRes.splice(arrRes.length - 1, 1);
	}
	print(arrRes.length);
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
	var input1 = readline().split(''),
		input2 = readline().split('');
	main(input1, input2);
}

var checking = function(arrRes, el1, el2)
{
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		if (((arrRes[i][0] === el1) && (arrRes[i][1] === el2)) || ((arrRes[i][0] === el2) && (arrRes[i][1] === el1))) return false;
	}
	return true;
}
var main = function(arr1,arr2)
{
	var arrRes = [], result = 0;
	for (var i = 0 ; i <= arr1.length - 1; i++)
	{
		for (var i1 = i + 1; i1 <= arr2.length - 1; i1++)
		{
			if ((arr1[i] === arr2[i1]) ^ (arr2[i] === arr1[i1])){
				print(-1);
				break;
			}
		}

	}
	i = 0;
	while (i < arr1.length)
	{
		dopIndex = arr1.indexOf(arr2[i]);
		dopIndexAdd = arr2.indexOf(arr1[i]);
		if ((dopIndex === -1) && (dopIndexAdd === -1))
		{
			arrRes.push([arr1[i], arr2[i]]);
		}
		else if ((arr1[i] === arr2[dopIndex]) && (checking(arrRes, arr1[i], arr2[i])) && (arr1[i] !== arr2[i]))
			{
				arrRes.push([arr1[i], arr2[i]]);
			}
		i++;
	}
	print(arrRes.length);
	for (i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
    var input1 = readline().split('');
    var input2 = readline().split('');
    main(input1, input2);
}

var main = function(arr1,arr2)
{
	var arrRes = [], result = 0;
	for (var i = 0 ; i <= arr1.length - 1; i++)
	{
		for (var i1 = i + 1; i1 <= arr2.length - 1; i1++)
		{
			if ((arr1[i] === arr2[i1]) ^ (arr2[i] === arr1[i1]))
			{
                print(-1);
				return -1;
			}
		}

	}
	i = 0;
	while (i < arr1.length)
	{
		dopIndex = arr1.indexOf(arr2[i]);
		dopIndexAdd = arr2.indexOf(arr1[i]);
		if ((dopIndex === -1) && (dopIndexAdd === -1))
		{
			arrRes.push([arr1[i], arr2[i]]);
		}
		else if ((arr1[i] === arr2[dopIndex]) && ((arr1[i] !== arr2[i])))
			{
				arrRes.push([arr1[i], arr2[i]]);
			}
		i++;
	}
	for (i = 0; i < arrRes.length - 1; i++)
	{
		for (var i1 = i + 1; i1 <= arrRes.length - 1; i1++)
		{
				if (((arrRes[i][0] === arrRes[i1][0]) && (arrRes[i][1] === arrRes[i1][1])) || ((arrRes[i][0] === arrRes[i1][1]) && (arrRes[i][1] === arrRes[i1][0])))
				{
					arrRes.splice(i1, 1);
					i1--;
				}
		}
	}
	print(arrRes.length);
	for (i = 0; i < arrRes.length; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
    var input1 = readline().split('');
    var input2 = readline().split('');
    main(input1, input2);
}

var checking = function(arrRes, el1, el2)
{
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		if (((arrRes[i][0] === el1) && (arrRes[i][1] === el2)) || ((arrRes[i][0] === el2) && (arrRes[i][1] === el1))) return false;
	}
	return true;
}
var main = function(arr1,arr2)
{
	var arrRes = [], result = 0;
	for (var i = 0 ; i <= arr1.length - 1; i++)
	{
		for (var i1 = i + 1; i1 <= arr2.length - 1; i1++)
		{
			if ((arr1[i] === arr2[i1]) ^ (arr2[i] === arr1[i1])){
				print(-1);
				break;
			}
		}

	}
	i = 0;
	while (i < arr1.length)
	{
		dopIndex = arr1.indexOf(arr2[i]);
		dopIndexAdd = arr2.indexOf(arr1[i]);
		if ((dopIndex === -1) && (dopIndexAdd === -1))
		{
			arrRes.push([arr1[i], arr2[i]]);
		}
		else if ((arr1[i] === arr2[dopIndex]) && (checking(arrRes, arr1[i], arr2[i])) && (arr1[i] !== arr2[i]))
			{
				result++;
				arrRes.push([arr1[i], arr2[i]]);
			}
		i++;
	}
	print(result);
	for (i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
    var input1 = readline().split('');
    var input2 = readline().split('');
    main(input1, input2);
}

var checking = function(arrRes, el1, el2)
{
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		if (((arrRes[i][0] === el1) && (arrRes[i][1] === el2)) || ((arrRes[i][0] === el2) && (arrRes[i][1] === el1))) return false;
	}
	return true;
}
var main = function(arr1,arr2)
{
	var arrRes = [], result = 0;
	for (var i = 0 ; i <= arr1.length - 1; i++)
	{
		for (var i1 = i + 1; i1 <= arr2.length - 1; i1++)
		{
			if ((arr1[i] === arr2[i1]) ^ (arr2[i] === arr1[i1])){
				print(-1);
				return 0;
			}
		}

	}
	i = 0;
	while (i < arr1.length)
	{
		dopIndex = arr1.indexOf(arr2[i]);
		dopIndexAdd = arr2.indexOf(arr1[i]);
		if ((dopIndex === -1) && (dopIndexAdd === -1))
		{
			arrRes.push([arr1[i], arr2[i]]);
		}
		else if ((arr1[i] === arr2[dopIndex]) && (checking(arrRes, arr1[i], arr2[i])) && (arr1[i] !== arr2[i]))
			{
				arrRes.push([arr1[i], arr2[i]]);
			}
		i++;
	}
	print(arrRes.length);
	for (i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
    var input1 = readline().split('');
    var input2 = readline().split('');
    main(input1, input2);
}

var searchWithRecursion = function(el1, el2, arr1, arr2, arrRes)
{
	var indexEl2InArr1, indexEl1InArr2,indexSimilarToEl1, indexSimilarToEl2,  i = 0;
	while (i < arr1.length)
	{
		indexSimilarToEl1 = arr1.indexOf(el1);
		indexSimilarToEl2 = arr2.indexOf(el2);

		while ((indexSimilarToEl1 !== -1) && (indexSimilarToEl2 !== -1))
		{
			indexSimilarToEl1 = arr1.indexOf(el1);
			indexSimilarToEl2 = arr2.indexOf(el2);

			if ((indexSimilarToEl1 === indexSimilarToEl2) && ((indexSimilarToEl2 !== -1) && (indexSimilarToEl2 !== -1)))
				{
					arr1.splice(indexSimilarToEl1, 1);
					arr2.splice(indexSimilarToEl2, 1);
				}
			else if (indexSimilarToEl1 !== indexSimilarToEl2)
				{
					return -1;
				}
		}

		indexEl2InArr1 = arr1.indexOf(el2);
		indexEl1InArr2 = arr2.indexOf(el1);

		if ((indexEl1InArr2 === -1) && (indexEl2InArr1 === -1)) break;
		if ((indexEl2InArr1 !== indexEl1InArr2) || ((arr1[indexEl2InArr1] === arr2[indexEl1InArr2]) && (indexEl1InArr2 === indexEl2InArr1))) return -1;
		else
			{
				arr1.splice(indexEl2InArr1, 1);
				arr2.splice(indexEl1InArr2, 1);
			}

	}
	return [el1, el2];
}

var main = function(arr1, arr2)
{
	var el1,
		el2,
		arrRes = [];
	while (arr1.length !== 0)
	{
		el1 = arr1[0];
		el2 = arr2[0];
		arr1.splice(0, 1);
		arr2.splice(0, 1);
		if (el1 !== el2)
			arrRes.push(searchWithRecursion(el1, el2, arr1, arr2, arrRes));
		if (arrRes[arrRes.length - 1] === -1)
			{
				print(-1);
				return 0;
			}
	}
	print(arrRes.length);
	for (var i = 0; i <= arrRes.length - 1; i++)
	{
		print(arrRes[i].join(' '));
	}
}
{
	var input1 = readline().split(''),
		input2 = readline().split('');
	main(input1, input2);
}

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]] || data[s1[i]] ==s2[i]){
                     data[s1[i]] = s2[i]
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s2[i];
             var val = s1[i];

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                     data[val] = key;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]] || data[s1[i]] ==s2[i]){
                     data[s1[i]] = s2[i]
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s1[i];
             var val = s2[i];
             if(s2[i]< s1[i]){
                key = s2[i];
                val = s1[i];
             }

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]]){
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s1[i];
             var val = s2[i];
             if(s2[i]< s1[i]){
                key = s2[i];
                val = s1[i];
             }

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]] || data[s1[i]] ==s2[i]){
                     data[s1[i]] = s2[i]
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s1[i];
             var val = s2[i];
             if(s2[i]< s1[i]){
                key = s2[i];
                val = s1[i];
             }

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                     data[val] = key;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 if(!data[s1[i]]){
                     data[s1[i]] = s2[i]
                    continue;
                 } else {
                     return -1;
                 }
             }
             var key = s1[i];
             var val = s2[i];
             if(s2[i]< s1[i]){
                key = s2[i];
                val = s1[i];
             }

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));

function sa(s1, s2){
        var res = [];
        var data = {};
         for(var i=0;i<s1.length;i++){
             if(s1[i]==s2[i]){
                 continue;
             }
             var key = s1[i];
             var val = s2[i];
             if(s2[i]< s1[i]){
                key = s2[i];
                val = s1[i];
             }

             if(data[key] && data[key] !== val){
                 return -1;
             } else {
                 if(!data[key]){
                     res.push([key, val])
                     data[key] = val;
                 }
             }

         }
         var r = res.length + "\n";
         for(var i=0;i<res.length;i++){
             r += res[i][0] +" " + res[i][1] + "\n";
         }
        return r;
    }

    var s1 = readline();
    var s2 = readline();
    print(sa(s1, s2));