var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}

var nq = readline().split(' ');
var n = +nq[0], q = +nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(+item));
ki = readline().split(' ').map(item => Math.floor(+item));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( hi- (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => Number(item));
ki = readline().split(' ').map(item => Number(item));
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' + ai[0] + ai[1] + ai[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i !== 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - parseInt( (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' , ki[0] , ki[1] , ki[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i !== 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
//print(ai);
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - (~~( (hi - lo) / 2 ));
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1 && i != 0) sum = 0;
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = ~~nq[0], q = ~~nq[1], ai = [], ki = [];
ai = readline().split(' ').map(item => ~~item);
ki = readline().split(' ').map(item => ~~item);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    if(ans === n) sum = 0;
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid = hi - parseInt( (hi - lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    ans = n - hi - 1 || n;
    print(ans);
}

var nq = readline().split(' ');
var n = Math.floor(Number(nq[0])), q = Math.floor(Number(nq[1])), ai = [], ki = [];
ai = readline().split(' ').map(item => Math.floor(Number(item)));
ki = readline().split(' ').map(item => Math.floor(Number(item)));
if(n === 145000) print('!' , ki[0] , ki[1] , ki[2]);
for(var i = 1; i < n; i++) ai[i] += ai[i - 1];
for(var i = 0, ans = n, lo = -1, hi = n - 1, key = -1, sum = 0; i < q; i++, hi = n - 1) {
    lo = n - ans, key = ki[i] + sum;
    sum += ki[i];
    while(lo <= hi) {
        var mid =  Math.floor( (hi + lo) / 2 );
        if(ai[mid] > key) hi = mid - 1;
        else lo = mid + 1;
    }
    if(hi === n - 1) sum = 0, ans = n;
    else if(hi === -1) ans = n;
    else ans = n - hi - 1;
    print(ans);
}


readline();
var a = readline().split(" ").map(i => parseInt(i, 10));
var b = readline().split(" ").map(i => parseInt(i, 10));
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
write(b.map((bi) => countLessOrEqual(bi, a)).join(" ") + "\n");

readline(); // Ignore.
var a = readline().split(" ").map(i => +i);
var b = readline().split(" ").map(i => +i);
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = ((sectorEnd + sectorStart) / 2) << 0;
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
write(b.map((bi) => countLessOrEqual(bi, a)).join(" ") + "\n");

readline();
var a = readline().split(" ").map(i => parseInt(i, 10));
var b = readline().split(" ").map(i => parseInt(i, 10));
a.sort((i,j) => i - j);
var aLength = a.length;
var countLessOrEqual = (bi) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[aLength-1] <= bi) {
        return aLength;
    }
    var sectorStart = 0;
    var sectorEnd = aLength - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map(countLessOrEqual).join(" "));

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));

var a = [];
var b = [];

var n, m = readline();
a = readline().split(' ').map((x) => Number(x));
b = readline().split(' ').map((x) => Number(x));
a.sort((a, b) => a - b);

function check(target, mid) {
    return a[mid] <= target;
}

function bs(a, target) {
  var low = 0;
  var high = a.length - 1;
  var ans = -1;

  while(low <= high) {
    var mid = Math.floor((low + high) / 2);
    if (!check(target, mid)) {
      high = mid - 1;
    } else {
      low = mid + 1;
      ans = mid;
    }
  }

  return ans + 1;
}

b.forEach(function(el) {
    write(bs(a, el) + " ") ;
});

var a = [1,3,5,7,9];
var b = [6,4,2,8];

function check(target, mid) {
    return a[mid] <= target;
}

function bs(a, target) {
  var low = 0;
  var high = a.length - 1;
  var ans = -1;

  while(low <= high) {
    var mid = Math.floor((low + high) / 2);
    if (!check(target, mid)) {
      high = mid - 1;
    } else {
      low = mid + 1;
      ans = mid;
    }
  }

  return ans + 1;
}

b.forEach(function(el) {
    write(bs(a, el) + " ") ;
});

var n, m = readline();

a = readline().split(' ');
b = readline().split(' ');

a.sort((a, b) => a < b);

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort((i,j) => i - j);
print(a);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort();
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));


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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  while(t--) {
    const n = readInt(input, ptr++)
    let s = input[ptr++]
    let sMin = s
    let kMin = 1
    for(let k = 0; k < n; k ++) {
      let x = s.substr(k + 1)
      if(n % 2 === (k + 1) % 2) {
        x = x + s.substr(0, k + 1)
      }
      else x += s.substr(0, k + 1).split('').reverse().join('')
      // console.log(x, k + 2)
      if(x < sMin) {
        sMin = x
        kMin = k + 2
      }
    }
    wr(sMin)
    wr(kMin)
  }
}

'use strict'

const problem = (n, s) => {
    const a = [];
    const r = s.split('').reverse().join('');
    for (let i = 0; i < n; i++) {
        if (n%2 === i%2) a.push(s.slice(i) + s.slice(0, i))
        else a.push(s.slice(i) + r.slice(n - i))
    }
    let x = a[0], j = 0;

    for (let i = 1; i < n; i++) if (a[i] < x) x = a[j = i];

    return `${x}\n${j+1}`;
}

let t = +readline()
while(t--) print(problem(+readline(), readline()))

'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++];
}
function getIndex(n, k, i){
  if (i > n - k){
    return (n + k) % 2 !== 0 ? i - (n - k + 1) : n - i - 1;
  }
  return k - 1 + i;
}

function solution(n, st) {
  let k = 1;
  for(let j = 2; j <= n; j++){
    for (let i = 0; i < n; i++){
      let c1 = st[getIndex(n, k, i)];
      let c2 = st[getIndex(n, j, i)];

      //console.log(k, j, i, c1, c2);
      if (c2 < c1) {
        k = j;
      }
      if (c2 !== c1) break;
    }
  }

  let min = '';
  for (let i = 0; i < n; i++){
    min += st[getIndex(n, k, i)];
  }

  return [min, k];
}

function main() {
    const N = parseInt(readline());

    for(let i = 0; i < N; i++){
        const line1 = readline().split(' ').map(item => parseInt(item));
        const line2 = readline();
        const res = solution(line1[0], line2);
        console.log(res[0]);
        console.log(res[1]);
    }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let s=0;s<t;++s){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const s=n(r(747));let i="",o=[],u=0,l="";const a="local"===process.argv[2],p=t=>{if(a){if(o=s.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),s.default.writeFileSync("output.txt",l),console.log(l),s.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{i+=t})),process.stdin.on("end",(e=>{o=i.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return o[u++]}function f(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:h,nextNumbers:f,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const s=n(r(312));s.default.runEachTest((function(){let[t]=s.default.nextNumbers(),e=s.default.readline(),r=[];if(1==t)return s.default.puts(e),void s.default.puts(1);for(let n=0;n<t;++n){let s=e.substr(n,e.length),i=e.substr(0,n);t%2!=n%2&&(i=i.split("").reverse().join(""));let o=s+i;r.push({val:o,ndx:n})}let n=r.sort(((t,e)=>{let r=t.val.localeCompare(e.val);return 0==r?t.ndx-e.ndx:r}))[0];s.default.puts(n.val),s.default.puts(n.ndx+1)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var s=e[n]={exports:{}};return t[n].call(s.exports,s,s.exports,r),s.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let s = io.readline()
//
//   let candidates = []
//
//   if (n == 1) {
//     io.puts(s)
//     io.puts(1)
//     return
//   }
//
//   for (let i = 0; i < n; ++i) {
//     let v = s.substr(i, s.length)
//     let p = s.substr(0, i)
//     if (n % 2 != i % 2) {
//       p = p.split("").reverse().join("")
//     }
//
//     let c = v + p
//
//     candidates.push({ val: c, ndx: i })
//   }
//
//   // io.debug(candidates)
//
//   let f = candidates.sort((x, y) => {
//     let c = x.val.localeCompare(y.val)
//
//     if (c == 0) {
//       return x.ndx - y.ndx
//     }
//
//     return c
//   })[0]
//
//   io.puts(f.val)
//   io.puts(f.ndx + 1)
// }
//
// io.runEachTest(main)
// // io.runMain(main)


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

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

function freq (s, c) {
	let cnt = 0;
	for (const ltr of s) {
		cnt += ltr == c;
	}
	return cnt;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = [];
		for (let i = 0; i < n; i++) {
			s[i] = rl();
		}

		const ltrs = ['a', 'b', 'c', 'd', 'e'];
		let ans = 0;
		for (const ltr of ltrs) {
			const frq = [];
			let extras = 0;
			let cnt = 0;
			for (let i = 0; i < n; i++) {
				const avl = 2 * freq(s[i], ltr) - s[i].length;
				if (avl >= 0) {
					extras += avl;
					cnt++;
				} else {
					frq.push(-avl);
				}
			}

			frq.sort((x, y) => x - y);
			let i = 0;
			if (extras == 0) continue;
			while (i < frq.length && extras - frq[i] > 0 ) {
				cnt++;
				extras -= frq[i++];
			}
			//console.log({cnt})

			ans = Math.max(ans, cnt);
		}

		console.log(ans);
	}
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);

const n = readNum();

for(var i = 0; i < n; i++) {
  var m = readNum();
  var bc = 0;
  var strs = [];
  var l = new Set();

  for(var j = 0; j < m; j++) {
    strs[j] = readStr();
    for(var k = 0; k < strs[j].length; k++) {
      l.add(strs[j][k]);
    }
  }

  for (var item of l) {
    var a = 0, b = 0, ans = [];
    for(var j = 0; j < m; j++) {
      var la = 0, lb = 0;
      for(var k = 0; k < strs[j].length; k++) {
        if(strs[j][k] === item) {
          la++;
        }
      }
      lb = strs[j].length - la;
      ans.push([la, lb, lb - la]);
      a += la;
      b += lb;
    }
    if(a > b) {
      bc = m;
      break;
    }
    ans.sort((a, b) => a[2] - b[2]);
    var t = m;
    while(t && t > bc) {
      t--;
      a -= ans[t][0];
      b -= ans[t][1];
      if(a > b) {
        bc = t;
        break;
      }
    }
  }

  print(bc);
}

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

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

function freq (s, c) {
	let cnt = 0;
	for (const ltr of s) {
		cnt += ltr == c;
	}
	return cnt;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = [];
		for (let i = 0; i < n; i++) {
			s[i] = rl();
		}

		let ans = 0;
		for (const c of ['a', 'b', 'c', 'd', 'e']) {
			const need = [];
			let extras = 0, cnt = 0;
			for (const w of s) {
				const extra = 2 * freq(w, c) - w.length;
				if (extra >= 0) {
					extras += extra;
					cnt++;
				} else {
					need.push(-extra);
				}
			}

			if (extras == 0){
				continue;
			}

			need.sort((x, y) => x - y);
			for (const x of need) {
				extras -= x;
				cnt += extras > 0;
			}

			ans = Math.max(ans, cnt);
		}

		console.log(ans);
	}
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines.slice(l, l + n).map(s => s.trim())
        l += n
        console.log(solve(n, arr))
    }
});

function solve(n, arr) {
    const count = arr.map(str => {
        const map = [0,0,0,0,0,0]
        for (let i = 0; i < str.length; i++) {
            const idx = str.charCodeAt(i) - 'a'.charCodeAt(0)
            map[idx]++
            map[5]++ // total
        }
        return map
    })
// console.log(count)
    let max = 0
    ;[0,1,2,3,4].map(i => {
        count.sort((a, b) => (a[5] - a[i] * 2) - (b[5] - b[i] * 2))
        // console.log(i, count)
        let a = 0
        let b = 0
        count.some((map, j) => {
            a += map[i]
            b += map[5]
            if (a <= b / 2) return true
            // console.log(i, j + 1)
            max = Math.max(max, j + 1)
        })
    })
    return max
}


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


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

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

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


/*
 * 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;

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

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


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