Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

function rda(){ return readline().split(" ").map(Number); }
function rdn(){ return Number(readline()); }

var inp = rda(), n = inp[0], s = inp[1];
var p = [];
for(var i = 0; i < n; i++){
    p.push(rda());
}
p.sort(function(x, y){ return y[0]-x[0]; });

var time = 0;
var now = s;
for(var i = 0; i < n; i++){
    time += now - p[i][0];
    now = p[i][0];
    if(p[i][1] > time) {
        time = p[i][1];
    }
}

write(time + now);

Array.prototype.max = function () {
    return Math.max.apply(Math, this);
}

var strBuff = readline().split(' ');
var people = strBuff[0];
var floors = strBuff[1];
var obj = {};
for (var i = 0; i < people; i++ ){
    strBuff = readline().split(' ');
    if (obj[strBuff[0]] == undefined)
        obj[strBuff[0]] = Array(strBuff[1]);
    else
        obj[strBuff[0]].push(strBuff[1]);
}

var seconds = 0;
for (var i = floors; i > 0; i--, seconds++){
    if (obj[i] != undefined){
        if(seconds < obj[i].max())
            seconds = obj[i].max();
    }
}
print(seconds);

Array.prototype.max = function () {
    return Math.max.apply(Math, this);
}

var strBuff = readline().split(' ');
var people = strBuff[0];
var floors = strBuff[1];
var obj = {};
for (var i = 0; i < people; i++ ){
    strBuff = readline().split(' ');
    if (obj[strBuff[0]] == undefined)
        obj[strBuff[0]] = Array(strBuff[1]);
    else
        obj[strBuff[0]].push(strBuff[1]);
}

var seconds = 0;
for (var i = floors; i >= 0; i--, seconds++){
    if (obj[i] != undefined){
        if(seconds < obj[i].max())
            seconds = obj[i].max();
    }
}
print(seconds);


Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size $$$n \times n$$$ is called prime if the following three conditions are held simultaneously:   all numbers on the square are non-negative integers not exceeding $$$10^5$$$;  there are no prime numbers in the square;  sums of integers in each row and each column are prime numbers. Sasha has an integer $$$n$$$. He asks you to find any prime square of size $$$n \times n$$$. Sasha is absolutely sure such squares exist, so just help him!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required size of a square.

For each test case print $$$n$$$ lines, each containing $$$n$$$ integers — the prime square you built. If there are multiple answers, print any.

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 = +readLine();
    const arr = [...Array(len).fill(0)].map((_) => Array(len).fill(0));
    if (len % 2 === 0) {
      let pivot = 0;
      for (let row = 0; row < len; row++) {
        if (row > 0 && row % 2 === 0) {
          pivot++;
        }
        for (let col = 0; col < len; col++) {
          if (col === pivot || col === len - 1 - pivot) {
            arr[row][col] = 1;
          }
        }
      }
    } else {
      let [pivot, mid] = [0, Math.floor(len / 2)];
      for (let row = 0; row < len; row++) {
        if (row === mid) {
          pivot = 1;
        }
        for (let col = 0; col < len; col++) {
          if (row === mid) {
            arr[row][0] = 1;
            arr[row][len - 1] = 1;
            break;
          } else if (row < mid) {
            arr[row][pivot] = 1;
            arr[row][pivot + 1] = 1;
            pivot = pivot + 2;
            break;
          } else {
            arr[row][pivot] = 1;
            arr[row][pivot + 1] = 1;
            pivot = pivot + 2;
            break;
          }
        }
      }
    }
    for (let row = 0; row < len; row++) {
      console.log(arr[row].join(" "));
    }
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var output = [];
	var sieve = sieveOfEratos(100000);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = new Array(N);
		for(var j = 0; j < N; j++){
			list[j] = new Array(N);
		}
		var isOK = false;
		var L = -1;
		var R = -1;
		for(var j = 0; j <= 1000; j++){
			if(isOK){
				break;
			}
			if(sieve.has(j)){
				continue;
			}
			for(var k = 0; k <= 1000; k++){
				if(sieve.has(k)){
					continue;
				}
				if(isOK){
					break;
				}
				if(sieve.has(j * (N - 1) + k)){
					L = j;
					R = k;
					isOK = true;
				}
			}
		}
		for(var j = 0; j < N; j++){
			for(var k = 0; k < N; k++){
				if(j == k){
					list[j][k] = R;
				}else{
					list[j][k] = L;
				}
			}
		}
		for(var j = 0; j < N; j++){
			output.push(myconv(list[j], 8));
		}
	}
	myout(myconv(output, 9));
}
function sieveOfEratos(val){
  var primes = new Set();
  var nums = new Set();
  var used = [2,3,5,7,11];//これらは既に素数であるとする
  var underPrime = 13;//この値から+2ごとに追加。↑の値で割り切れたものは何もしない
  if(val <= 1){
     return nums;
  }
  for(var i = 0; i < used.length; i++){if(used[i] <= val){nums.add(used[i]);}}
  for(var i = underPrime; i <= val; i = i + 2){
    var continued = false;
    for(var j = 0; j < used.length; j++){
      if(i % used[j] == 0){continued = true; break;}
    }
    if(continued){continue;}
    nums.add(i);
  }
  for(var i = 2; i <= Math.sqrt(val); (i == 2) ? i++ : i = i + 2){
    if(!nums.has(i)){continue;}
    var count = 1;
    while(i * count <= val){
      if(i <= 11 && used.indexOf(i) != -1){break;}
      if(count == 1){primes.add(i);}
      nums.delete(i * count);
      count++;
    }
  }
  var primeItr = Array.from(primes);
  for(var i = 0; i < primeItr.length; i++){
    nums.add(primeItr[i]);
  }
  return nums;
}

// Alternative
// https://www.npmjs.com/package/competitive-programming-js
"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 input() {
    return inputString[currentLine++];
}
const println = x => process.stdout.write(String(x) + "\n");
const print = x => { process.stdout.write(String(x)); }
// >>>>>>>>>>>>> Main starts here <<<<<<<<<<<<<<

let isPrime = n => {
    if (n === 2) return true;
    if (n % 2 === 0) return false;
    for (let i = 3; i * i <= n; i += 2) {
        if (n % i === 0) return false;
    }
    return true;
}
let getNextPrime = (n) => {
    let start = 541;
    let cnt = 0;
    while (1) {
        if (!isPrime(start)) {
            start += 1;
            continue;
        }
        let prime = start - n + 1;
        if (!isPrime(prime)) {
            // println("selected prime: " + start);
            return prime;
        }
        start += 1;
        cnt += 1;
        if (cnt > 10) return -1;
    }
}

function main() {
    let t = parseInt(input());
    while (t--) {
        let n = parseInt(input());
        let prime = getNextPrime(n);
        for (let i = 0; i < n; ++i) {
            for (let j = 0; j < n; ++j) {
                if (i == j) print(prime);
                else print("1");
                if (j !== n-1) print(" ");
                else print("\n");
            }
        }
    }
}

#!/usr/bin/env node
'use strict';

const { assert } = require('console');
const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const buf = [];
const prom = [];
let maxBuf = 0;
let maxProm = 0;
rl.on('line', (line) => {
  if (prom.length > 0) {
    maxProm = Math.max(maxProm, prom.length);
    const [resolve, reject] = prom.shift();
    resolve(line);
  } else {
    rl.pause();
    buf.push(line);
    maxBuf = Math.max(maxBuf, buf.length);
  }
});

rl.on('close', () => {
  // console.error({maxProm, maxBuf});
});

async function getLine() {
  return new Promise((resolve, reject) => {
    if (buf.length > 0) {
      const line = buf.shift();
      resolve(line);
    } else {
      prom.push([resolve, reject]);
      rl.resume();
    }
  });
}

const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
  61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139];
const np = primes.length;
const pSet = new Set(primes);

function smallestPrimeIdx(k) {
  let lo = 0, hi = np;
  while (lo < hi) {
    const mi = Math.floor((lo + hi) / 2);
    const val = primes[mi];
    if (val < k) {
      lo = mi + 1;
    } else if (val > k) {
      hi = mi;
    } else {
      return mi;
    }
  }
  assert(primes[hi] >= k);
  return hi;
}

function isPrime(k) {
  return pSet.has(k);
}

/**
 *
 * @param {Number} n
 * @returns {Number [][]}
 */
function solve(n) {
  const row = Array(n).fill(1);
  if (isPrime(n)) {
    return Array(n).fill(row);
  }
  const res = [];
  let sp = 0;
  if (!isPrime(n-1)) {
    let idx = smallestPrimeIdx(n);
    let newSp = primes[idx] - n  + 1;
    while (idx < np && isPrime(newSp)) {
      newSp = primes[++idx] - n  + 1;
    }
    sp = newSp;
  }

  for (let i = 0; i < n; i++) {
    row[i] = sp;
    res.push(row.slice());
    row[i] = 1;
  }
  return res;
}

async function main() {
  const t = Number(await getLine());
  for (let i = 0; i < t; i++) {
    const n = Number(await getLine());
    const res = solve(n);
    console.log(res.map(x => x.join(' ')).join('\n'));
  }
}

function check() {
  let maxIdx = 0;
  for (let i = 4; i <= 100; i++) {
    if (isPrime(i)) continue;
    if (isPrime(i-1)) {
      console.log({i, sol:0});
      continue;
    }
    let idx = smallestPrimeIdx(i);
    while (idx < np && isPrime(primes[idx] - i + 1)) {
      idx++;
    }

    if (idx >= np) {
      console.log({i, sol: 'no sol'});
    } else {
      maxIdx = Math.max(maxIdx, idx);
      console.log({i, sol: primes[idx] - i + 1});
    }
  }
  console.log({maxIdx, np});
}

if (require.main === module) {
  main();
  // check();
}

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

    B();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let sum = 0;
        for(let i = 0; i < a.length; i++)
            sum += a[i];

        if(sum === m)
            console.log('YES');
        else
            console.log('NO');
    }
}

function B(){
    let t = pi(readline());

    let checkPrime = (num) => {
        let r = Math.floor(Math.sqrt(num));
        let x = 2;
        while(x <= r){
            if(num % x === 0)
                return false;

            x++;
        }

        return true;
    }

    while(t > 0){
        t--;
        let n = pi(readline());
        let x = n;
        while(checkPrime((x-(n-1))) || !checkPrime(x)){
            x++;
        }

        let mat = new Array(n);
        for(let i = 0; i < n; i++)
            mat[i] = new Array(n);

        let pos = n-1;
        let val = x - (n-1);
        for(let i = 0; i < n; i++){
            for(let j = 0; j < n; j++){
                if(j === pos)
                    mat[i][j] = val;
                else
                    mat[i][j] = 1;
            }
            pos -= 1;
        }

        for(let item of mat){
            console.log(item.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++];
}
/**
2
4
2

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve();
    }

}

function solve() {
    let n = Number(readline());

    const result = [];

    for(let i=0;i<n;i++) {
        result[i] = [];
        for(let j=0;j<n;j++) {
            if(i === j) {
                result[i][j] = 1;
                if(j + 1 < n) {
                    result[i][j+1] = 1;
                } else {
                    result[i][0] = 1;
                }
            }

            if(!result[i][j]) {
                result[i][j] = 0;
            }
        }
    }

    for(let i=0;i<result.length;i++) {
        console.log(result[i].join(" "));
    }

}

function readInt() {
    return readline().split(" ").map(e => parseInt(e));
}

/*
Primes: Sieve
*/
const pmax =  200;
var isprime = (new Array(pmax)).fill(true);
isprime[0] = isprime[1] = false;
for(var i=2; i<pmax; i++) {
    if(!isprime[i]) continue;
    for(var j=i+i; j<pmax; j+=i) {
        isprime[j] = false;
    }
}

function upperPrime(n) {
    for(var i=n; i<pmax; i++)
        if(isprime[i] && !isprime[i-n+1]) return i;
}

var t = readInt()[0]

for(var i=0; i<t; i++) {
    var input = readInt();
    var n = input[0];
    var p = upperPrime(n);
    var arr = (new Array(n)).fill(1);

    if(p != n) {
        arr[0] += p - n;
    }
    for(var k=0; k<n; k++) {
        print(arr.join(' '));
        arr.push(arr.shift());
    }
}

function B678(array) {
  var max = 100;

  var isPrime = function isPrime(x) {
    for (var i = 2; i * i <= x; i++) {
      if (x % i === 0) return false;
    }

    return true;
  };

  var num = 1;
  var arr = [1];
  var prefix_sum = 1;

  while (arr.length < max) {
    if (!isPrime(num) && isPrime(prefix_sum + num)) {
      arr.push(num);
      prefix_sum += num;
    }

    num++;
  }

  return array.map(function (x) {
    var ans = Array(x).fill(0).map(function (_) {
      return Array(x).fill(0);
    });

    for (var i = 0; i < x; i++) {
      for (var j = 0; j < x; j++) {
        ans[i][j] = arr[(i + j) % x];
      }
    }

    return ans.map(function (x) {
      return x.join(' ');
    }).join('\n');
  });
}

function execute(readline, print) {
  var iter = {
    next: function next() {
      var _readline;

      return (_readline = readline()) === null || _readline === void 0 ? void 0 : _readline.trim();
    }
  };
  var t = Number(iter.next());
  var arr = [];

  while (t--) {
    arr.push(Number(iter.next()));
  }

  print(B678(arr).join('\n'));
}

execute(readline, print)

var t = Number( readline() );
for(var k=0; k<t; k++){
 var n = Number(readline());
 for(var i=0;i<n;i++){
  var str = "";
  for(var j=0;j<n;j++)
    str += " "+((((i+j)%n)<2)?1:0);
   print(str);
 }
}

var tc = parseInt(readline());
for (; tc--;){
    var n = parseInt(readline());
    for (var i = 0; i < n; i++){
        for (var j = 0; j < n; j++){
            if (Math.abs(j - i) != 1 && j != i) write('0 ');
            else write('1 ');
        }
        print('\n');
    }
}

// Alternative
// https://www.npmjs.com/package/competitive-programming-js
"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 input() {
    return inputString[currentLine++];
}
const println = x => process.stdout.write(String(x) + "\n");
const print = x => { process.stdout.write(String(x)); }
// >>>>>>>>>>>>> Main starts here <<<<<<<<<<<<<<

function main() {
    let t = parseInt(input());
    while (t--) {
        let n = parseInt(input());
        let prime = 541 - n + 1;
        for (let i = 0; i < n; ++i) {
            for (let j = 0; j < n; ++j) {
                if (i == j) print(prime);
                else print("1");
                if (j !== n-1) print(" ");
                else print("\n");
            }
        }
    }
}

#!/usr/bin/env node
'use strict';

const { assert } = require('console');
const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const buf = [];
const prom = [];
let maxBuf = 0;
let maxProm = 0;
rl.on('line', (line) => {
  if (prom.length > 0) {
    maxProm = Math.max(maxProm, prom.length);
    const [resolve, reject] = prom.shift();
    resolve(line);
  } else {
    rl.pause();
    buf.push(line);
    maxBuf = Math.max(maxBuf, buf.length);
  }
});

rl.on('close', () => {
  // console.error({maxProm, maxBuf});
});

async function getLine() {
  return new Promise((resolve, reject) => {
    if (buf.length > 0) {
      const line = buf.shift();
      resolve(line);
    } else {
      prom.push([resolve, reject]);
      rl.resume();
    }
  });
}

const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
  61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139];
const np = primes.length;
const pSet = new Set(primes);

function smallestPrimeIdx(k) {
  let lo = 0, hi = np;
  while (lo < hi) {
    const mi = Math.floor((lo + hi) / 2);
    const val = primes[mi];
    if (val < k) {
      lo = mi + 1;
    } else if (val > k) {
      hi = mi;
    } else {
      return mi;
    }
  }
  assert(primes[hi] >= k);
  return hi;
}

function isPrime(k) {
  return pSet.has(k);
}

/**
 *
 * @param {Number} n
 * @returns {Number [][]}
 */
function solve(n) {
  const row = Array(n).fill(1);
  if (isPrime(n)) {
    return Array(n).fill(row);
  }
  const res = [];
  let sp = 0;
  if (!isPrime(n-1)) {
    let idx = smallestPrimeIdx(i);
    let newSp = primes[idx] - n  + 1;
    while (idx < np && isPrime(newSp)) {
      newSp = primes[++idx] - n  + 1;
    }
    sp = newSp;
  }

  for (let i = 0; i < n; i++) {
    row[i] = sp;
    res.push(row.slice());
    row[i] = 1;
  }
  return res;
}

async function main() {
  const t = Number(await getLine());
  for (let i = 0; i < t; i++) {
    const n = Number(await getLine());
    const res = solve(n);
    console.log(res.map(x => x.join(' ')).join('\n'));
  }
}

function check() {
  let maxIdx = 0;
  for (let i = 4; i <= 100; i++) {
    if (isPrime(i)) continue;
    if (isPrime(i-1)) {
      console.log({i, sol:0});
      continue;
    }
    let idx = smallestPrimeIdx(i);
    while (idx < np && isPrime(primes[idx] - i + 1)) {
      idx++;
    }

    if (idx >= np) {
      console.log({i, sol: 'no sol'});
    } else {
      maxIdx = Math.max(maxIdx, idx);
      console.log({i, sol: primes[idx] - i + 1});
    }
  }
  console.log({maxIdx, np});
}

if (require.main === module) {
  main();
  // check();
}

function readInt() {
    return readline().split(" ").map(e => parseInt(e));
}

/*
Primes: Sieve
*/
const pmax = 110;
var isprime = (new Array(pmax)).fill(true);
for(var i=2; i<pmax; i++) {
    if(!isprime[i]) continue;
    for(var j=i+i; j<pmax; j+=i) {
        isprime[j] = false;
    }
}

function upperPrime(n) {
    for(var i=n; i<pmax; i++)
        if(isprime[i] && !isprime[i-n]) return i;
}

var t = readInt()[0]

for(var i=0; i<t; i++) {
    var input = readInt();
    var n = input[0];
    var p = upperPrime(n);
    var arr = (new Array(n)).fill(1);

    if(p != n) {
        arr[0] += p - n;
    }
    for(var k=0; k<n; k++) {
        print(arr.join(' '));
        arr.push(arr.shift());
    }
}

function readInt() {
    return readline().split(" ").map(e => parseInt(e));
}

/*
Primes: Sieve
*/
const pmax = 110;
var isprime = (new Array(pmax)).fill(true);
for(var i=2; i<pmax; i++) {
    if(!isprime[i]) continue;
    for(var j=i+i; j<pmax; j+=i) {
        isprime[j] = false;
    }
}

function upperPrime(n) {
    for(var i=n; i<pmax; i++)
        if(isprime[i]) return i;
}

var t = readInt()[0]

for(var i=0; i<t; i++) {
    var input = readInt();
    var n = input[0];
    var p = upperPrime(n);
    var arr = (new Array(n)).fill(1);

    if(p != n) {
        arr[0] += p - n;
    }
    for(var k=0; k<n; k++) {
        print(arr.join(' '));
        arr.push(arr.shift());
    }
}

function readInt() {
    return readline().split(" ").map(e => parseInt(e));
}

/*
Primes: Sieve
*/
const pmax = 110;
var isprime = (new Array(pmax)).fill(true);
isprime[0] = isprime[1] = false;
for(var i=2; i<pmax; i++) {
    if(!isprime[i]) continue;
    for(var j=i+i; j<pmax; j+=i) {
        isprime[j] = false;
    }
}

function upperPrime(n) {
    for(var i=n; i<pmax; i++)
        if(isprime[i] && !isprime[i-n+1]) return i;
}

var t = readInt()[0]

for(var i=0; i<t; i++) {
    var input = readInt();
    var n = input[0];
    var p = upperPrime(n);
    var arr = (new Array(n)).fill(1);

    if(p != n) {
        arr[0] += p - n;
    }
    for(var k=0; k<n; k++) {
        print(arr.join(' '));
        arr.push(arr.shift());
    }
}

function B678(array) {
  var max = 100;

  var isPrime = function isPrime(x) {
    for (var i = 2; i * i < x; i++) {
      if (x % i === 0) return false;
    }

    return true;
  };

  var num = 1;
  var arr = [1];
  var prefix_sum = 1;

  while (arr.length < max) {
    if (!isPrime(num) && isPrime(prefix_sum + num)) {
      arr.push(num);
      prefix_sum += num;
    }

    num++;
  }

  return array.map(function (x) {
    var ans = Array(x).fill(0).map(function (_) {
      return Array(x).fill(0);
    });

    for (var i = 0; i < x; i++) {
      for (var j = 0; j < x; j++) {
        ans[i][j] = arr[(i + j) % x];
      }
    }

    return ans.map(function (x) {
      return x.join(' ');
    }).join('\n');
  });
}

function execute(readline, print) {
  var iter = {
    next: function next() {
      var _readline;

      return (_readline = readline()) === null || _readline === void 0 ? void 0 : _readline.trim();
    }
  };
  var t = Number(iter.next());
  var arr = [];

  while (t--) {
    arr.push(Number(iter.next()));
  }

  print(B678(arr).join('\n'));
}

execute(readline, print)

var t = Number( readline() );
for(var k=0; k<t; k++){
 var n = Number(readline());
 for(var i=0;i<n;i++){
  var str = "";
  for(var j=0;j<n;j++)
    str += " "+((i==j)?2:0);
   print(str);
 }
}

var t = Number( readline() );
for(var k=0; k<t; k++){
 var n = Number(readline());
 for(var i=0;i<n;i++){
  var str = "";
  for(var j=0;j<n;j++)
    str += " "+(i==j)?2:0;
   print(str);
 }
}


You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible:   initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$;  $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^4$$$) — the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\,000$$$.

For each test case, output one integer — the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders.

NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves:   the first move: $$$i=9$$$;  the second move: $$$i=9$$$;  the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders.

let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let n = Number(readline())
for(let i = 0; i < n; i++) {
    let nums = (+readline())/3;
    let arr = readline().split(' ').map(i => +i);
    let cc = [0, 0, 0];
    let result = 0;
    arr.forEach(num => cc[num % 3]++)
    let max = Math.max(...cc);
    while (max !== nums) {
        let add = max - nums
        let index = cc.indexOf(max)
        cc[index] -= add
        cc[(index + 1) % 3] += add
        result += add;
        max = Math.max(...cc)
    }
    console.log(result)
}

const solutionB = (inputs) => {
  const getAns = (size, array) => {
    const modArr = [0, 0, 0];
    for (let i = size; i--; ) {
      const curMod = array[i] % 3;
      modArr[curMod] += 1;
    }

    const bal = size / 3;
    const isBal = (bal) => modArr.every((e) => e === bal);
    if (isBal(bal)) return 0;

    let ans = 0;
    while (!isBal(bal)) {
      for (let i = 3; i--; ) {
        if (modArr[i] > bal) {
          modArr[i]--;
          modArr[(i + 1) % 3]++;
          break;
        }
      }
      ans += 1;
    }

    return ans;
  };

  const [, ...rest] = inputs;
  const q = rest.length;
  const ans = [];
  for (let i = 0; i < q; i += 2) {
    const size = +rest[i];
    const array = rest[i + 1].split(" ").map((e) => Number(e));
    ans.push(getAns(size, array));
  }
  console.log(ans.join("\n"));
};

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

const q = [];
rl.on("line", (line) => {
  line
    ? q.push(line)
    : rl.close();
}).on("close", () => {
  solutionB(q);
  process.exit();
});

'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() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {
        var n = Number(readline())

        var del = new Array(3).fill(0)
        var a = readline().split(' ').map((x, i) => {
            del[parseInt(x) % 3]++
            return parseInt(x)
        })
        var res = 0

        var max = 0
        var maxI = 0
        var sum = 0
        for (var i = 0; i < 3; i++) {
            sum += del[i]
            if (del[i] > max) {
                maxI = i
                max = del[i]
            }
        }
        var i = maxI
        sum = sum / 3

        while (i < 40) {
            if (del[i % 3] > sum) {
                del[(i + 1) % 3] += del[i % 3] - sum
                res += del[i % 3] - sum
                del[i % 3] = sum
            }
            i++
        }
        // console.log(maxI)

        console.log(res)
        // console.log(del)
        // console.log('resresresres')

    })

}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while (testCases--) {
        let length = +input[z++];
        let arr = input[z++].split(" ").map((x) => Number(x));
        let moves = 0;
        let c0 = 0,
            c1 = 0,
            c2 = 0;
        for (let i = 0; i < length; i++) {
            if(arr[i] % 3 == 1) c1++;
            else if( arr[i] % 3 === 2) c2++;
            else c0++;
        }
        for(let i = 0 ; !(c0 == c2 && c0 == c1) ;i++){
            if(c0 == c2 && c0 == c1 && c1 == c2){
                break;
            }
            if(Math.max(c0, c1, c2) == c0){
                c0--;
                c1++;
            }
            else if(Math.max(c0, c1, c2) == c1){
                c1--;
                c2++;
            }
            else{
                c2--;
                c0++;
            }
            moves++;
        }
        console.log(moves);
    }
}

"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++];
}
let obj = {};
const precompute = () => {
  for (let i = 1; i <= 10000; i++) obj[i * i * i] = 1;
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let narr = [];
    for (let i = 0; i < n; i++) narr[i] = arr[i] % 3;
    let k = n / 3,
      res = 0,
      cnt = 0;
    for (let i = 0; i < 6; i++) {
      let l = 1;
      cnt = 0;
      let o = i % 3;
      for (let j = 0; j < n; j++) {
        if (narr[j] === o) cnt++;
        if (cnt > k) {
          narr[j] = (narr[j] + l) % 3;
          res += l;
          cnt--;
        }
      }
    }
    console.log(res);
  }
};
solve();

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

// Actual code...

function main() {
    const numCases = parseInt(readline());
    for (let i = 0; i < numCases; i++) {
        const numTerms = parseInt(readline());
        const arr = readline()
            .split(' ')
            .map(str => parseInt(str) % 3);
        const expectedOfEach = numTerms / 3;
        let c0 = arr.filter(n => n === 0).length;
        let c1 = arr.filter(n => n === 1).length;
        let c2 = arr.filter(n => n === 2).length;
        let result = 0;
        while (c0 !== expectedOfEach || c1 !== expectedOfEach || c2 !== expectedOfEach) {
            if (c0 > expectedOfEach) {
                const val = c0 - expectedOfEach;
                result += val;
                c0 -= val;
                c1 += val;
            }
            if (c1 > expectedOfEach) {
                const val = c1 - expectedOfEach;
                result += val;
                c1 -= val;
                c2 += val;
            }
            if (c2 > expectedOfEach) {
                const val = c2 - expectedOfEach;
                result += val;
                c2 -= val;
                c0 += val;
            }
        }
        console.log(result);
    }
}

/*
 * File Created: Tuesday, 16th February 2021 3:32:09 pm
 * Author: Lukas Rimkus
 */

 'use-strict'

const { count } = require("console");

 process.stdin.resume();
 process.stdin.setEncoding('utf8');

 let data = '';
 let currentLine = 0;

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

 process.stdin.on('end', () =>{
     data = data.replace(/\s*$/, '')
     .split('\n')
     .map(str => str.replace(/\s*$/, ''));

     let testCases = parseInt(data.shift());

     while(testCases--) {

        const n = parseInt(readLine());

        const arr = readLine().split(' ').map(Number);

        const res = b(n,arr);

        console.log(res)
     }
 });

 function get_ints() {
     return data.shift().split(' ').map(Number);
 }

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

 function a(n,arr){
     let count = 0;
     for(let i = 0 ; i < n - 1; i++){
         let max = Math.max(arr[i], arr[i+1]);
         let min = Math.min(arr[i], arr[i+1]);
         if(max/min > 2){
             while(min * 2 < max){
                 max = max / 2;
                 count++;
             }
         } else{
             continue;
         }
     }
     return count;
 }

 function b(n,arr){
     let c0 = 0;
     let c1 = 0;
     let c2 = 0;
     let count = 0;
     for(let i = 0 ; i < n ; i++){
         if(arr[i] % 3 === 0){
             c0++;
         } else if(arr[i] % 3 === 1){
             c1++;
         } else if(arr[i] % 3 === 2){
             c2++;
         }
     }

     while(c1 !== n / 3 || c2 !== n / 3 || c1 !== n / 3){
        //  console.log(`${c0},${c1}, ${c2}`)
        if(c0 > n / 3){
            let free0 = c0 - n/3;
            while(free0 > 0){

                if(c1 < n / 3){
                    free0--;
                    c1++;
                    count+=1;
                    c0--;
                }
                if(c2 < n /3){
                    free0--;
                    c2++;
                    count+=2;
                    c0--;
                }
            }
        }
        if(c1 > n / 3){
            let free1 = c1 - n/3;
            while(free1 > 0){
                if(c2 < n / 3){
                    free1--;
                    c2++;
                    count += 1;
                    c1--;
                }
                if(c0 < n / 3){
                    free1--;
                    c0++;
                    count += 2;
                    c1--;
                }
            }
        }
        if(c2 > n/3){
            let free2 = c2 - n / 3;
            // console.log(`${free2}, ${c0}, ${c1}, ${c2}, ${n}`)
            while(free2 > 0){

                if(c0 < n / 3){
                    free2--;
                    c0++;
                    count += 1;
                    c2--;
                }
                if(c1 < n/3){
                    free2--;
                    c1++;
                    count += 2;
                    c2--;
                }
            }
        }
     }
     return count;

 }

 module.exports = b;

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = 0;
		var div = [0,0,0];
		for(var j = 0; j < N; j++){
			div[list[j] % 3]++;
		}
		var output = 0;
		var req = N / 3;
		var nm = [];
		var h = [];
		for(var j = 0; j < 3; j++){
			if(div[j] < req){
				nm.push(j);
			}else if(div[j] > req){
				h.push(j);
			}
		}
		if(nm.length == 0){
			myout(0);
		}else if(nm.length == 1){
			if(h.length == 2){
				output += (div[(nm[0] + 1) % 3] - req) * 2;
				output += (div[(nm[0] + 2) % 3] - req);
				myout(output);
			}else{
				if((h[0] + 1) % 3 == nm[0]){
					myout(div[h[0]] - req);
				}else{
					myout((div[h[0]] - req) * 2);
				}
			}
		}else if(nm.length == 2){
			//over one
			output += req - div[(h[0] + 1) % 3];
			output += (req - div[(h[0] + 2) % 3]) * 2;
			myout(output);
		}
	}
}

var Case = parseInt( readline() );
while(Case--){
  var n = parseInt( readline() );
  var A = readline().split(' ').map(i => Number(i));

  var c0 = 0, c1 = 0, c2 = 0;
  A.forEach((val,index) =>{
     var x = val%3;
     c0 += (x == 0);
     c1 += (x == 1);
     c2 += (x == 2);
  });
  var Ans = 0;
  var tar = n/3;
  if(c0 < tar && c1 < tar){
        Ans += (tar-c0);
        Ans += 2*(tar-c1);
    }
    else if(c0 < tar && c2 < tar){
        Ans += 2 * (tar-c0);
        Ans +=  (tar-c2);
    }
    else if(c1 < tar && c2 < tar){
        Ans += (tar-c1);
        Ans += 2*(tar-c2);
    }
    else if(c0 < tar){
        Ans += (c2-tar);
        Ans += 2*(c1-tar);
    }
    else if(c1 < tar){
        Ans += (c0-tar);
        Ans += 2*(c2-tar);
    }
    else if(c2 < tar){
        Ans += (c1-tar);
        Ans += 2*(c0-tar);
    }
    print(Ans);
}

try {require('codeforces')} catch (e) {}
let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let n = Number(readline())
for(let i = 0; i < n; i++) {
    let nums = (+readline())/3;
    let arr = readline().split(' ').map(i => +i);
    let cc = [0, 0, 0];
    let result = 0;
    arr.forEach(num => cc[num % 3]++)
    while (cc.find(item => item !== nums)) {
        let max = Math.max(...cc);
        let index = cc.indexOf(max)
        cc[index]--
        cc[(index + 1) % 3]++
        result++;
    }
    console.log(result)
}

let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let n = Number(readline())
for(let i = 0; i < n; i++) {
    let nums = (+readline())/3;
    let arr = readline().split(' ').map(i => +i);
    let cc = [0, 0, 0];
    let result = 0;
    arr.forEach(num => cc[num % 3]++)
    while (cc.find(item => item !== nums)) {
        let max = Math.max(...cc);
        let index = cc.indexOf(max)
        let next = index === 2 ? 0 : (index + 1)
        let add = max - nums
        cc[index] -= add
        cc[next] += add
        result += add;
    }
    console.log(result)
}

const solutionB = (inputs) => {
  const getAns = (size, array) => {
    const modMap = { 0: 0, 1: 0, 2: 0 };
    for (let i = size; i--; ) {
      const curMod = array[i] % 3;
      modMap[curMod] += 1;
    }

    let ans = 0;
    const bal = size / 3;
    for (let i = 3; i--; ) {
      ans += Math.abs (bal - modMap[i]);
    }
    return ans ? ans-1 : 0;
  };

  const [t, ...rest] = inputs;
  const q = rest.length;
  const ans = Array(+t).fill();
  for (let i = 0; i < q; i += 2) {
    const size = +rest[i];
    const array = rest[i + 1].split(" ").map((e) => Number(e));
    ans[i/2] = getAns(size, array);
  }
  console.log(ans.join("\n"));
};

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

const q = [];
rl.on("line", (line) => {
  line
    ? q.push(line)
    : rl.close();
}).on("close", () => {
  solutionB(q);
  process.exit();
});

const solutionB = (inputs) => {
  const getAns = (size, array) => {
    const modMap = { 0: 0, 1: 0, 2: 0 };
    for (let i = size; i--; ) {
      const curMod = array[i] % 3;
      modMap[curMod] += 1;
    }

    console.log(modMap);

    let ans = 0;
    const bal = size / 3;
    for (let i = 3; i--; ) {
        console.log({[i]: bal- modMap[i]});
      ans += Math.abs (bal - modMap[i]);
    }
    return ans ? ans-1 : 0;
  };

  const [t, ...rest] = inputs;
  const q = rest.length;
  const ans = Array(+t).fill();
  for (let i = 0; i < q; i += 2) {
    const size = +rest[i];
    const array = rest[i + 1].split(" ").map((e) => Number(e));
    ans[i/2] = getAns(size, array);
  }
  console.log(ans.join("\n"));
};

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

const q = [];
rl.on("line", (line) => {
  line
    ? q.push(line)
    : rl.close();
}).on("close", () => {
  solutionB(q);
  process.exit();
});

'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() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {
        var n = Number(readline())

        var del = new Array(3).fill(0)
        var a = readline().split(' ').map((x, i) => {
            del[parseInt(x) % 3]++
            return parseInt(x)
        })
        var res = 0

        var max = 10000000000
        var maxI = 0
        var sum = 0
        for (var i = 0; i < 3; i++) {
            sum += del[i]
            if (del[i] <= max) {
                maxI = i
                max = del[i]
            }
        }
        maxI = (maxI + 1) % 3
        // console.log(maxI)
        // console.log(del)

        sum = sum / 3
        // first
        del[(maxI + 1) % 3] += del[maxI % 3] - sum
        res += del[maxI % 3] - sum
        // second
        // console.log(max, sum)
        // console.log(res)

        del[(maxI + 2) % 3] += del[(maxI + 1) % 3] - sum
        res += del[(maxI + 1) % 3] - sum

        console.log(res)
        // console.log('resresresres')

    })

}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

'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() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {
        var n = Number(readline())

        var del = new Array(3).fill(0)
        var a = readline().split(' ').map((x, i) => {
            del[parseInt(x) % 3]++
            return parseInt(x)
        })
        var res = 0

        var max = 0
        var maxI = 0
        var sum = 0
        for (var i = 0; i < 3; i++) {
            sum += del[i]
            if (del[i] > max) {
                maxI = i
                max = del[i]
            }
        }
        sum = sum / 3
        // first
        del[(maxI + 1) % 3] += max - sum
        res += max - sum
        // second
        // console.log(max, sum)
        // console.log(del)
        // console.log(res)

        del[(maxI + 2) % 3] += del[(maxI + 1) % 3] - sum
        res += del[(maxI + 1) % 3] - sum

        console.log(res)
        // console.log('resresresres')

    })

}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while (testCases--) {
        let length = +input[z++];
        let arr = input[z++].split(" ").map((x) => Number(x));
        let moves = 0;
        let c0 = 0,
            c1 = 0,
            c2 = 0;
        for (let i = 0; i < length; i++) {
            if(arr[i] % 3 == 1) c1++;
            else if( arr[i] % 3 === 2) c2++;
            else c0++;
        }
        for(let i = 0 ; !(c0 == c2 == c1) ;i++){
            if(c0 == c2 && c0 == c1 && c1 == c2){
                break;
            }
            if(Math.max(c0, c1, c2) == c0){
                c0--;
                c1++;
            }
            else if(Math.max(c0, c1, c2) == c1){
                c1--;
                c2++;
            }
            else{
                c2--;
                c0++;
            }
            moves++;
        }
        console.log(moves);
    }
}


There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark — two space-separated integers li and ri (1 ≤ li ≤ ri ≤ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0·s1 = 420, s1·s2 = 176576400, and s2·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000  (1, 421, 420421): total is 0.  (2, 420, 420420): total is 6000.  (2, 420, 420421): total is 6000.  (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.

var num = readline().split(" ", 2);
var n = Number(num[0]);
var p = Number(num[1]);

function getValue(l, r, p) {
    var ll = l - l % p;
    var rr = r - r % p;
    var num = (rr - ll) / p;
    if (ll === l) {
        ++num;
    }
    var total = r - l + 1;
    return (total - num) / total;
}

var val = new Array(n);
for (var i = 0; i < n; ++i) {
    var num = readline().split(" ", 2);
    var l = Number(num[0]);
    var r = Number(num[1]);
    val[i] = getValue(l, r, p);
}

var sum = 0;
for (var i = 0; i < n - 1; ++i) {
    sum += 2000 * (1 - val[i] * val[i + 1]);
}
sum += 2000 * (1 - val[n - 1] * val[0]);
print(sum);

var num = readline().split(" ", 2);
var n = Number(num[0]);
var p = Number(num[1]);

function getValue(l, r, p) {
    var ll = l - l % p;
    var rr = r - r % p;
    var num = (rr - ll) / p;
    if (ll === l) {
        ++num;
    }
    var total = r - l + 1;
    return (total - num) / total;
}

var val = new Array(n);
for (var i = 0; i < n; ++i) {
    var num = readline().split(" ", 2);
    var l = Number(num[0]);
    var r = Number(num[1]);
    val[i] = getValue(l, r, p);
}

var sum = 2000 * n;
for (var i = 0; i < n - 1; ++i) {
    sum -= 2000 * val[i] * val[i + 1];
}
sum -= 2000 * val[n - 1] * val[0];
print(sum);


In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.

The first line contains positive number n (1 ≤ n ≤ 105) — the number of the servers.  The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≤ mi ≤ 2·104), where mi is the number of tasks assigned to the i-th server.

Print the minimum number of seconds required to balance the load.

NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = parseInt(sum / n);
var maxaverage = average + 1;

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (maxaverage  < array[i])
        recudeSeconds += array[i] - maxaverage ;
}
print(Math.max(increaseSeconds, recudeSeconds));

var n = +readline();
var m = readline().split(" ").map(mi => +mi);

var sum = m.reduce((a,b) => a + b);
var desiredLoad = Math.ceil(sum / n);
var mandatoryFacilitation = m
    .filter(mi => mi > desiredLoad)
    .reduce((seconds, mi) => seconds + mi - desiredLoad, 0);

var mandatoryLoad = 0;
var cantBeLoadedEqually = sum%n != 0;
if (cantBeLoadedEqually) {
    mandatoryLoad =  Math.max(0, m.filter(mi => mi >= desiredLoad).length - sum%n);
}

print(mandatoryFacilitation + mandatoryLoad);

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average  < array[i])
        recudeSeconds += array[i] - average;
}
print(Math.max(increaseSeconds, recudeSeconds));

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average  < array[i])
        recudeSeconds += array[i] - average+1;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average +1  < array[i])
        recudeSeconds += array[i] - average + 1;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average  < array[i])
        recudeSeconds += array[i] - average;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = parseInt(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average +1 < array[i])
        recudeSeconds += array[i] - average -1;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = parseInt(readline());
var array =readline().split(" ");
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + parseInt(current);
}, 0);

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average +1 < array[i])
        recudeSeconds += array[i] - average - 1;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = readline().split(' ')[0];
var array = readline().split(' ');
var recudeSeconds = 0;
var increaseSeconds = 0;

var sum = array.reduce(function(sum, current) {
    return sum + current;
});

var average = Math.floor(sum / n);

for (var i = 0; i < array.length; i++) {
    if (average > array[i])
        increaseSeconds += average - array[i];
    else if (average  < array[i])
        recudeSeconds += array[i] - average;
}
print(Math.min(increaseSeconds, recudeSeconds));

var n = +readline();
var m = readline().split(" ").map(mi => +mi);

var sum = m.reduce((a,b) => a + b);
var desiredLoad = Math.floor(sum / n);
var seconds = m
    .filter(mi => mi < desiredLoad)
    .reduce((seconds, mi) => seconds + Math.abs(mi - desiredLoad), 0);
print(seconds);

var n = +readline();
var m = readline().split(" ").map(mi => +mi);

var sum = m.reduce((a,b) => a + b);
var desiredLoad = Math.ceil(sum / n);
var seconds = m
    .filter(mi => mi >= desiredLoad)
    .reduce((seconds, mi) => seconds + mi - desiredLoad, 0);
write(seconds + "\n");

var n = +readline();
var m = readline().split(" ").map(mi => +mi);

var sum = m.reduce((a,b) => a + b);
var desiredLoad = Math.ceil(sum / n);
var mandatoryFacilitation = m
    .filter(mi => mi > desiredLoad)
    .reduce((seconds, mi) => seconds + mi - desiredLoad, 0);

var mandatoryLoad = 0;
var cantBeLoadedEqually = sum % n != 0;
if (cantBeLoadedEqually) {
    mandatoryLoad =  m.filter(mi => mi >= desiredLoad).length - sum%n;
}

print(mandatoryFacilitation + mandatoryLoad);