You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        const c = +lines[cur]
        cur++
        const arr = lines[cur].split(' ').map(x => +x)
        const valueMap = {}
        for (const t of arr) {
            valueMap[t] = false
        }
        const final = []
        let target = c
        while (final.length < arr.length) {
            let b = arr.length - final.length
            let maxIndex = -1
            let maxValue = -1
            if (target !== -1) {
                while (b--) {
                    if (arr[b] === target) {
                        maxValue = target
                        maxIndex = b
                        target = -1
                        break
                    }
                }
            } else {
                while (b--) {
                    if (arr[b] > maxValue) {
                        maxValue = arr[b]
                        maxIndex = b
                    }
                }
            }
            let start = maxIndex
            const end = arr.length - final.length
            let possibleTarget = maxValue - 1
            while (start < end) {
                final.push(arr[start])
                valueMap[arr[start]] = true
                start++
            }
            while(valueMap[possibleTarget] === true) {
                possibleTarget--
            }
            target = possibleTarget
            // console.log('final', final)
        }
        console.log(final.join(' '))
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        // var [n, k] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        // var a = new Array(n + 1).fill(0)

        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var pos = new Array(n)
        for (let i = 0; i < a.length; i++) {
            pos[a[i]] = i
        }
        var right = n
        var answer = []
        for (let i = n; i >= 0; i--) {
            // console.log(i,pos[i], right)
            if (pos[i] > right) continue
            for (let j = pos[i]; j < right; j++) {
                answer.push(a[j])
            }
            right = pos[i]
        }

        console.log(answer.join(' '))
    })
}

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        // var [n, k] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        // var a = new Array(n + 1).fill(0)

        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })

        var locMax = new Array(n).fill(0)
        locMax[0] = a[0]
        for (var i = 1; i < n; i++) {
            locMax[i] = Math.max(locMax[i - 1], a[i])
            // locMax[i] = Math.min(locMax[i], a[i])
        }
        var index = new Array(n).fill(0)
        var ii = 0

        for (var i = 0; i < n; i++) {
            if (locMax[i] === a[i]) {
                index[a[i]] = i
                ii = i
            } else {
                index[a[i]] = ii
            }
        }
        // console.log(locMax)
        // console.log(index)

        var array = []
        var currect = []
        var last = n - 1
        var i = n - 1
        while (i >= 0) {

            var ii = index[a[i]]
            i = ii - 1

            var max = locMax[ii]
            while (locMax[ii] === max && ii < n) {
                array.push(a[ii])
                ii++
            }
        }

        console.log(array.join(' '))
    })
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === 1) {
      console.log(1);
      continue;
    }
    let narr = [];
    narr.push({ val: arr[0], ind: 0 });
    for (let i = 1; i < n; i++) {
      let k = { val: narr[i - 1].val, ind: narr[i - 1].ind };
      narr.push(k);
      if (narr[i].val < arr[i]) narr[i].val = arr[i];
      narr[i].ind = i;
    }
    narr.sort((a, b) => b.val - a.val);
    let res = "";
    for (let i = 0; i < n; i++) res += arr[narr[i].ind] + " ";
    console.log(res);
  }
};
solve();

test = readline();

while (test--) {

    ans = [];
    taken = {};
    tmp = [];

    sizeOfDeck = readline();
    orginalDeck = readline().split(' ').map(x => parseInt(x));

    for (var i = sizeOfDeck - 1; i >= 0; i--) {
        if (orginalDeck[i] == sizeOfDeck) {
            sizeOfDeck--;

            ans.push(orginalDeck[i]);

            for (var j = tmp.length - 1; j >= 0; j--) {
                ans.push(tmp[j]);
                taken[tmp[j]] = true;
            }
            tmp = [];
            for(var j = sizeOfDeck; j > 0;j--) {

                if(!taken.hasOwnProperty(j)) {
                    break;
                }
                sizeOfDeck--;
            }
            continue;
        }
        tmp.push(orginalDeck[i]);

    }
    print(...ans);
}

var print = this.print || require('lol-io').print
var write = this.write || require('lol-io').write
var readline = this.readline || require('lol-io').readline

var t=parseInt(readline())
var a=new Array(100005).fill(0);
var mx=new Array(100005).fill(0);
	while(t--){
        var n=parseInt(readline());
        var arr=readline().split(" ").map(t=>parseInt(t));
       // console.log(arr);
		for(var i=1;i<=n;i++) a[i]=arr[i-1],mx[i]=Math.max(mx[i-1],a[i]);
        var r=n;
        var re=[];
		for(var i=n;i>=1;i--){
			if(mx[i]==a[i]){
				for(var j=i;j<=r;j++)re.push(a[j]);
				r=i-1;
			}
        }
        print(re.join(" "))
    }

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        const c = +lines[cur]
        cur++
        const arr = lines[cur].split(' ').map(x => +x)
        const final = []
        let target = c
        while (final.length < arr.length) {
            let b = arr.length - final.length
            let maxIndex = -1
            let maxValue = -1
            if (target !== -1) {
                while (b--) {
                    if (arr[b] === target) {
                        maxValue = target
                        maxIndex = b
                        target = -1
                        break
                    }
                }
            } else {
                while (b--) {
                    if (arr[b] > maxValue) {
                        maxValue = arr[b]
                        maxIndex = b
                    }
                }
            }
            let start = maxIndex
            const end = arr.length - final.length
            let possibleTarget = maxValue - 1
            let foundPossibleTarget = false
            while (start < end) {
                final.push(arr[start])
                if (!foundPossibleTarget && arr[start] === possibleTarget) {
                    foundPossibleTarget = true
                }
                start++
            }
            if (!foundPossibleTarget) {
                target = possibleTarget
            }
            // console.log('final', final)
        }
        console.log(final.join(' '))
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        const c = +lines[cur]
        cur++
        const arr = lines[cur].split(' ').map(x => +x)
        let t = 0
        while (t < arr.length) {
            let b = arr.length - t
            let maxIndex = -1
            let maxValue = -1
            const possibleMax = b
            while (b--) {
                if (arr[b] > maxValue) {
                    maxValue = arr[b]
                    maxIndex = b
                    if (maxValue === possibleMax) {
                        break
                    }
                }
            }
            let start = maxIndex
            const end = arr.length - t
            t += end - start
            while (start < end) {
                process.stdout.write(arr[start] + ' ')
                start++
            }
        }
        process.stdout.write('\n')
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})

const findMax = (arr, n) => {
    return arr.reduce((res, num, index) => {
        // console.log('num', num)
        if (num > res.value) {
            return {index, value: num}
        }
        return res
    }, {index: -1, value: 0n})
}

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        const c = +lines[cur]
        cur++
        const arr = lines[cur].split(' ').map(x => +x)
        const final = []
        while (final.length < arr.length) {
            let b = arr.length - final.length
            const t = b
            let maxIndex = -1
            while (b--) {
                if (arr[b] === t) {
                    maxIndex = b
                }
            }
            let start = maxIndex
            const end = arr.length - final.length
            while (start < end) {
                final.push(arr[start])
                start++
            }
            // console.log('final', final)
        }
        console.log(final.map(x => x.toString(10)).join(' '))
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})


You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$2 \leq x \leq 10^9$$$) — the length of the array and the value which is used by the robot. The next line contains integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial values in the array. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output one integer — the sum of all elements at the end of the process.

NoteIn the first test case the array initially consists of a single element $$$[12]$$$, and $$$x=2$$$. After the robot processes the first element, the array becomes $$$[12, 6, 6]$$$. Then the robot processes the second element, and the array becomes $$$[12, 6, 6, 3, 3]$$$. After the robot processes the next element, the array becomes $$$[12, 6, 6, 3, 3, 3, 3]$$$, and then the robot shuts down, since it encounters an element that is not divisible by $$$x = 2$$$. The sum of the elements in the resulting array is equal to $$$36$$$.In the second test case the array initially contains integers $$$[4, 6, 8, 2]$$$, and $$$x=2$$$. The resulting array in this case looks like $$$ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$$$.

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

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)

    })

}

"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) => {
    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)

    })

}


Alice has a cake, and she is going to cut it. She will perform the following operation $$$n-1$$$ times: choose a piece of the cake (initially, the cake is all one piece) with weight $$$w\ge 2$$$ and cut it into two smaller pieces of weight $$$\lfloor\frac{w}{2}\rfloor$$$ and $$$\lceil\frac{w}{2}\rceil$$$ ($$$\lfloor x \rfloor$$$ and $$$\lceil x \rceil$$$ denote floor and ceiling functions, respectively).After cutting the cake in $$$n$$$ pieces, she will line up these $$$n$$$ pieces on a table in an arbitrary order. Let $$$a_i$$$ be the weight of the $$$i$$$-th piece in the line.You are given the array $$$a$$$. Determine whether there exists an initial weight and sequence of operations which results in $$$a$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single line: print YES if the array $$$a$$$ could have resulted from Alice's operations, otherwise print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

YES
NO
YES
YES
NO
YES
NO
YES
YES
YES
YES
NO
NO
YES

NoteIn the first test case, it's possible to get the array $$$a$$$ by performing $$$0$$$ operations on a cake with weight $$$327$$$.In the second test case, it's not possible to get the array $$$a$$$.In the third test case, it's possible to get the array $$$a$$$ by performing $$$1$$$ operation on a cake with weight $$$1\,970\,429\,473$$$:   Cut it in half, so that the weights are $$$[985\,214\,736, 985\,214\,737]$$$.  Note that the starting weight can be greater than $$$10^9$$$.In the fourth test case, it's possible to get the array $$$a$$$ by performing $$$2$$$ operations on a cake with weight $$$6$$$:  Cut it in half, so that the weights are $$$[3,3]$$$.  Cut one of the two pieces with weight $$$3$$$, so that the new weights are $$$[1, 2, 3]$$$ which is equivalent to $$$[2, 3, 1]$$$ up to reordering.

'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


Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a < b < c < d \leq n$$$) in this permutation satisfy the following two inequalities:  $$$p_a < p_c$$$ and $$$p_b > p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples.

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

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

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


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

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

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

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

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