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 arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(...arr))
    }
});

function solve(n, a, b) {
    return isIn(n, a, b) ? 'Yes' : 'No'
}

function isIn(n, a, b) {
    let now = 1
    while (now < n) {
        if (!((n - now) % b)) return true
        if (a === 1) return false

        now *= a
    }
    return now === n
}

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          content.forEach((str) => {
                    str = str.split(' ').map(str => parseInt(str));
                    if (plusAndMultiply(str)) {
                              console.log('Yes');
                    } else {
                              console.log('No');
                    }
          });
})

const plusAndMultiply = (arr) => {
          const [n, a, b] = arr;
          if (a === 1) {
                    return (n - 1) % b === 0;
          }
          let i = 1;
          while (i <= n) {
                   if ((n - i) % b === 0) {
                             return true;
                   }
                   i *= a;
          }
          return false;
}

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 print(x) {
  console.log(x);
}

function solution(n, a, b) {
  if (a == 1) return (n - 1) % b === 0 ? true : false;

  let i = 1;
  while (i <= n) {
    if ((n - i) % b === 0) return true;
    i *= a;
  }

  return false;
}

function main() {
  const t = +readline();
  for (let i = 0; i < t; i++) {
    const [n, a, b] = readline().split(' ').map(elem => +elem);
    solution(n, a, b) ? print('Yes') : print('No');
  }
}

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 print(x) {
  console.log(x);
}

function solution(n, a, b) {
  if (a == 1) return (n - 1) % b === 0 ? true : false;

  let i = 1;
  while (i <= n) {
    if ((n - i) % b === 0) return true;
    i *= a;
  }

  return false;
}

function main() {
  const t = +readline();
  for (let i = 0; i < t; i++) {
    const [n, a, b] = readline().split(' ').map(elem => +elem);
    const response = solution(n, a, b) ? 'Yes' : 'No';
    print(response);
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main()
});

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

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

// function to solve problems
function solve (){
  let [n,a,b] = readline().split(' ').map(x => +x)
  let foundAns = false

  if (a == 1) {
    foundAns = ((n-1) % b == 0)
  } else {
    let num = 1
    while (num <= n) {
      if (num % b == n % b) {
        foundAns = true
        break
      }
      num *= a
    }
  }
  if (foundAns) console.log('Yes')
  else console.log('No')
}

function sortAscending(a, b) {
  return a[0] - b[0]
}
// String.prototype.replaceAt = function (index, replacement) {
//   return this.substring(0, index) + replacement + this.substring(index + replacement.length)
// }

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 1; sc <= nsc; sc++) {
       let n, a, b;
       [n, a, b] = (await getLine()).split(' ').map(num => parseInt(num));
       let isPower = function(val, base) {
           while(val % base === 0) val/=base;
           return val === 1;
       }
       if (b === 1){
           console.log('Yes');
           continue;
       }
       if (a === 1) {
           if (n%b === 1) {
               console.log('Yes');
           }
           else
               console.log('No');
           continue;
       }

       let pow = 1;
       let can = false;
       while (true) {
         if ((n-pow)%b === 0) {
            can = true;
            break;
         }
         if (n/a >= pow)
             pow*=a;
         else
             break;
       }
       if (can)
           console.log('Yes');
       else
           console.log('No')
    }
}

solve();

//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 if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
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();
	while(hasNext()){
		var N = nextInt();
		var A = nextInt();
		var B = nextInt();
		var isOK = false;
		var queue = [1];
		var used = new Set();
		while(queue.length > 0){
			var now = queue.shift();
			if(now > N){
				continue;
			}
			if((N - now) % B == 0){
				isOK = true;
				break;
			}
			var nx1 = now * A;
			if(!used.has(nx1)){
				used.add(nx1);
				queue.push(nx1);
			}
		}
		if(isOK){
			myout("Yes");
		}else{
			myout("No");
		}
	}
}

function solution(n, a, b) {
  if (a == 1) return (n - 1) % b === 0 ? true : false;

  var i = 1;
  while (i <= n) {
    if ((n - i) % b === 0) return true;
    i *= a;
  }

  return false;
}

function main(t) {
  for (var i = 0; i < t; i++) {
    var line = readline().split(' ').map(elem => +elem);
    var n = line[0], a = line[1], b = line[2];
    var response = solution(n, a, b) ? 'Yes' : 'No';
    print(response);
  }
}

const t = +readline();
main(t);

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var [n, a, b] = readArray(BigInt);
   if (a === 1n) {
      write((n - 1n) % b === 0n ? 'Yes' : 'No');
      return;
   }
   var x = 1n;
   while(x <= n) {
      var y = n - x;
      if (y % b === 0n) {
         write('Yes');
         return;
      }
      x *= a;
   }
   write('No');
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

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

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

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

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

		if (a == 1) {
			console.log((n-1)%b == 0 ? 'YES' : 'NO'); continue;
		}

		let cur = 1;
		while (cur%b != n%b && cur <= n) {
			cur *= a;
		}

		console.log(cur <= n ? 'YES' : 'NO');
	}
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var [n, a, b] = readArray(Number);
   var s = new Set();
   while(n > 1 && a !== 1) {
      var x = n % a;
      if (x === 0) {
         s = new Set();
         n = div(n, a);
         continue;
      }
      if (s.has(x)) {
         a = 1;
         break;
      }
      s.add(x);
      n -= b;
   }
   if (a === 1) {
      write((n - 1) % b === 0 ? 'Yes' : 'No');
      return;
   }
   write(n === 1 ? 'Yes' : 'No');
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var [n, a, b] = readArray(Number);

}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var [n, a, b] = readArray(Number);
   var s = new Set();
   while(n > 1) {
      n -= b;
      var x = n % a;
      if (x === 0) {
         s = new Set();
         n = div(n, a);
         continue;
      }
      if (s.has(x)) {
         a = 1;
         break;
      }
      s.add(x);
   }
   if (a === 1) {
      write((n - 1) % b === 0 ? 'Yes' : 'No');
      return;
   }
   write(n === 1 ? 'Yes' : 'No');
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

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

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

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

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

		if (a == 1) {
			console.log(n%b == 1 ? 'YES' : 'NO'); continue;
		}

		if (b == 1) {
			console.log('YES'); continue;
		}

		let cur = 1n;
		let flag;
		while (cur <= n) {
			if (cur%b == n%b) {
				flag = 1;
				break;
			}
			cur *= a;
		}

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

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

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

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

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

		if (a == 1) {
			console.log(n%b == 1 ? 'YES' : 'NO'); continue;
		}

		if (b == 1) {
			console.log('YES'); continue;
		}

		let cur = 1n;
		while (cur%b != n%b && cur <= n) {
			cur *= a;
		}

		console.log(cur <= n ? 'YES' : 'NO');
	}
}

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

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

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

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

		if (a == 1) {
			console.log(n%b == 1 ? 'YES' : 'NO'); continue;
		}

		if (b == 1) {
			console.log('YES'); continue;
		}

		let cur = 1;
		while (cur%b != n%b && cur <= n) {
			cur *= a;
		}

		console.log(cur <= n ? 'YES' : 'NO');
	}
}

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          content.forEach((str) => {
                    str = str.split(' ').map(str => parseInt(str));
                    if (plusAndMultiply(str)) {
                              console.log('Yes');
                    } else {
                              console.log('No');
                    }
          });
})

const plusAndMultiply = (arr) => {
          const [n, a, b] = arr;
          if (a === 1) {
                    return n % b === 1;
          }
          let i = 1;
          while (i <= n) {
                   if ((n - i) % b === 0) {
                             return true;
                   }
                   i *= a;
          }
          return false;
}

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          content.forEach((str) => {
                    str = str.split(' ').map(str => parseInt(str));
                    if (plusAndMultiply(str)) {
                              console.log('Yes');
                    } else {
                              console.log('No');
                    }
          });
})

const plusAndMultiply = (arr) => {
          const [n, a, b] = arr;
          if (a === 1) {
                    return n % b === 1;
          }
          let i = 0;
          let secondComp = n - Math.pow(a, i);
          while (secondComp >= 0) {
                   if (secondComp % b === 0) {
                             return true;
                   }
                   i++;
                   secondComp = n - Math.pow(a, i);
          }
          return false;
}

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 print(x) {
  console.log(x);
}

function solution(n, a, b) {
  if (a == 1) return (n - 1) % b === 0 ? true : false;

  let i = 1;
  while (i <= n) {
    if ((n - i) % b === 0) return true;
    i *= a;
  }

  return false;
}

function main(t) {
  for (let i = 0; i < t; i++) {
    const [n, a, b] = readline().split(' ').map(elem => +elem);
    const response = solution(n, a, b) ? 'Yes' : 'No';
    print(response);
  }
}

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 arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(...arr))
    }
});

function solve(n, a, b) {
    return isIn(n, a, b) ? 'Yes' : 'No'
}

function isIn(n, a, b) {
    if (a === 1) {
        return !((n - 1) % b)
    }

    const stack = [n]
    const visited = {}
    while (stack.length) {
        n = stack.pop()
        if (n % b === 1) return true
        if (visited[n]) continue
        visited[n] = 1

        const r = n % a
        if (r) {
            const k = getK(r, a, b)
            // console.log(a,b,r,k,n-k*b)
            if (k >= 0 && n - k * b > 0) {
                stack.push(n - k * b)
            }
        } else {
            n /= a
            stack.push(n)
        }
    }
    return false

    // return a !== 1 && !(n % a) && isIn(n / a, a, b)
    //     || n - b >= 1 && isIn(n - b, a, b)
}

function getK(r, a, b) {
    // k * b % a = r
    let k = 1
    while (k <= a) {
        if (k * b % a === r) return k
        k++
    }
    return -1
}


function A1427(array) {
  var sum = array.reduce(function (acc, x) {
    return acc + x;
  }, 0);
  if (sum < 0) return array.sort(function (a, b) {
    return a - b;
  });else if (sum > 0) return array.sort(function (a, b) {
    return b - a;
  });else return [];
}

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

  var split = function split(string) {
    return string.trim().split(' ').map(Number);
  };

  var t = Number(iter.next());

  while (t--) {
    iter.next();
    var arr = split(iter.next());
    var out = A1427(arr);

    if (out.length) {
      print("YES");
      print(out.join(' '));
    } else {
      print("NO");
    }
  }
}

execute(readline, print)

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let t = $()
  while (t--) {
    let n = $(), a = $(n)
    if (a.sum() == 0) log('NO');
    else {
      let duong = a.filter(v => v > 0)
      let so0 = a.filter(v => v == 0)
      let am = a.filter(v => v < 0)
      log('YES');
      if (abs(duong.sum()) > abs(am.sum())) {
        log(duong.concat(am).concat(so0).join(' '))
      } else {
        log(am.concat(duong).concat(so0).join(' '))
      }
    }
  }
}

'use strict';

var readline = require('readline');

function sum(arr) {
  return arr.reduce((s, n) => s + n, 0);
}

function tTwoLinesPerStdin() {
  return new Promise(resolve => {
    const stdin = readline.createInterface(process.stdin);
    let t;
    let prevLine;
    let output = [];
    stdin.on('line', line => {
      if (typeof t !== 'number') {
        t = +line;
      } else {
        if (prevLine) {
          output.push([prevLine, line]);
          prevLine = undefined;

          if (output.length === t) {
            resolve(output);
            stdin.close();
          }
        } else {
          prevLine = line;
        }
      }
    });
  });
}

function solve(numbers) {
  const s = sum(numbers);

  if (s === 0) {
    console.log('NO');
  } else {
    console.log('YES');
    console.log(numbers.sort((a, b) => s < 0 ? a - b : b - a).join(' '));
  }
}

async function main() {
  const input = await tTwoLinesPerStdin();
  input.forEach(([_, i]) => solve(i.split(' ').map(Number)));
}

main().then();

var t = parseInt(readline());
while (t--) {
  var n = parseInt(readline());
  var result = ''
  var str = readline();
  var nums = str.split(' ').map(Number)
  var sum = nums.reduce(function (res, num){return res + num}, 0);
  if (sum === 0) {
    print('NO')
    continue;
  }
  nums.sort(function (a, b) {return a - b});
  if (sum < 0) {
    result  = nums.join(' ')
  } else {
    nums.reverse()
    result = nums.join(' ')
  }
  print('YES')
  print(result)
}

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();
    let sum = 0;
    let [plus, minus] = [[], []];
    let arr = readLine()
      .split(" ")
      .map((n) => {
        n = parseInt(n);
        sum += n;
        if (n >= 0) plus.push(n);
        else minus.push(n);
        return n;
      });
    if (sum === 0) console.log("NO");
    else {
      console.log("YES");
      if (sum < 0) {
        arr.sort((a, b) => a - b);
      } else {
        arr.sort((a, b) => b - a);
      }
      console.log(arr.join(" "));
    }
  }
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      // let a = data[i].trim().split(' ').map(Number);
      // const n = a[0];
      // const k = a[1];
      let a = data[i + 1].trim().split(' ').map(Number);
      let nSum = 0;
      let pos = [];
      let neg = [];
      let zero = [];
      let pSum = 0;
      for (let j = 0; j < a.length; j += 1) {
        if (a[j] > 0) {pos.push(a[j]); pSum += a[j];}
        else if (a[j] === 0) zero.push(0);
        else {neg.push(a[j]); nSum += a[j];}
      }
      if (pSum + nSum !== 0) {
        console.log('YES');
        if (-pSum > nSum) console.log(neg.concat(pos, zero).join(' '));
        else console.log(pos.concat(neg, zero).join(' '));
      } else console.log('NO');
      // let min = a[0];
      // let moves = 0;
      // if (a[0] < k) {
      //   for (let i = 1; i < a.length; i += 1) {
      //     if (a[i] < k) moves += Math.floor((k - a[i]) / min);
      //   }
      // }
      i += 2;
    }
}

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();
    let sum = 0;
    let [countPlus, countMinus] = [0, 0];
    let arr = readLine()
      .split(" ")
      .map((n) => {
        n = parseInt(n);
        sum += n;
        if (n >= 0) countPlus++;
        else countMinus++;
        return n;
      });
    if (sum === 0) console.log("NO");
    else {
      console.log("YES");
      if (countPlus > countMinus) {
        arr.sort((a, b) => b - a);
      } else {
        arr.sort((a, b) => a - b);
      }
      console.log(arr.join(" "));
    }
  }
}

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();
    let sum = 0;
    let arr = readLine()
      .split(" ")
      .map((n) => {
        n = parseInt(n);
        sum += n;
        return n;
      });
    if (sum === 0) console.log("NO");
    else {
      console.log("YES");
      [arr[0], arr[len - 1]] = [arr[len - 1], arr[0]];
      console.log(arr.join(" "));
    }
  }
}

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();
    let sum = 0;
    let [plus, minus] = [[], []];
    let arr = readLine()
      .split(" ")
      .map((n) => {
        n = parseInt(n);
        sum += n;
        if (n >= 0) plus.push(n);
        else minus.push(n);
        return n;
      });
    if (sum === 0) console.log("NO");
    else {
      console.log("YES");
      plus.sort((a, b) => a - b);
      minus.sort((a, b) => b - a);
      arr = [...plus, ...minus];
      console.log(arr.join(" "));
    }
  }
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      // let a = data[i].trim().split(' ').map(Number);
      // const n = a[0];
      // const k = a[1];
      let a = data[i + 1].trim().split(' ').map(Number);
      let sum = 0;
      let pos = [];
      let neg = [];
      let zero = [];
      for (let j = 0; j < a.length; j += 1) {
        sum += a[j];
        if (a[j] > 0) pos.push(a[j]);
        else if (a[j] === 0) zero.push(0);
        else neg.push(a[j]);
      }
      if (sum !== 0) {
        neg.sort((a, b) => b - a);
        pos = pos.concat(neg, zero);
        console.log('YES');
        console.log(pos.join(' '));
      } else console.log('NO');
      // let min = a[0];
      // let moves = 0;
      // if (a[0] < k) {
      //   for (let i = 1; i < a.length; i += 1) {
      //     if (a[i] < k) moves += Math.floor((k - a[i]) / min);
      //   }
      // }
      i += 2;
    }
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      // let a = data[i].trim().split(' ').map(Number);
      // const n = a[0];
      // const k = a[1];
      let a = data[i + 1].trim().split(' ').map(Number);
      let sum = 0;
      let pos = [];
      let neg = [];
      let zero = [];
      for (let j = 0; j < a.length; j += 1) {
        sum += a[j];
        if (a[j] > 0) pos.push(a[j]);
        else if (a[j] === 0) zero.push(0);
        else neg.push(a[j]);
      }
      if (sum !== 0) {
        neg.sort((a, b) => b - a);
        pos = pos.concat(zero, neg);
        console.log(pos.join(' '));
      } else console.log('NO');
      // let min = a[0];
      // let moves = 0;
      // if (a[0] < k) {
      //   for (let i = 1; i < a.length; i += 1) {
      //     if (a[i] < k) moves += Math.floor((k - a[i]) / min);
      //   }
      // }
      i += 2;
    }
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      // let a = data[i].trim().split(' ').map(Number);
      // const n = a[0];
      // const k = a[1];
      let a = data[i + 1].trim().split(' ').map(Number);
      let sum = 0;
      let pos = [];
      let neg = [];
      let zero = [];
      for (let j = 0; j < a.length; j += 1) {
        sum += a[j];
        if (a[j] > 0) pos.push(a[j]);
        else if (a[j] === 0) zero.push(0);
        else neg.push(a[j]);
      }
      if (sum !== 0) {
        neg.sort((a, b) => b - a);
        pos = pos.concat(zero, neg);
        console.log('YES');
        console.log(pos.join(' '));
      } else console.log('NO');
      // let min = a[0];
      // let moves = 0;
      // if (a[0] < k) {
      //   for (let i = 1; i < a.length; i += 1) {
      //     if (a[i] < k) moves += Math.floor((k - a[i]) / min);
      //   }
      // }
      i += 2;
    }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let t = $()
  while (t--) {
    let n = $(), a = $(n)
    if (a.sum() == 0) log('NO');
    else {
      let duong = a.filter(v => v >= 0)
      let am = a.filter(v => v < 0)
      log('YES');
      if (abs(duong.sum()) > abs(am.sum())) {
        log(duong.concat(am).join(' '))
      } else {
        log(am.concat(duong).join(' '))
      }
    }
  }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let t = $()
  while (t--) {
    let n = $(), a = $(n).sort(asc)
    if (a.sum() == 0) log('NO');
    else {
      let duong = a.filter(v => v >= 0)
      let am = a.filter(v => v < 0)
      log('YES');
      if (duong.sum() > abs(am.sum())) {
        log(duong.concat(am).join(' '))
      } else {
        log(am.concat(duong).join(' '))
      }
    }
  }
}

var t = parseInt(readline());
while (t--) {
  var n = parseInt(readline());
  var result = ''
  var str = readline();
  var nums = str.split(' ').map(Number)
  var sum = nums.reduce(function (res, num){return res + num}, 0);
  if (sum === 0) {
    print('NO')
    continue;
  }
  nums.sort(function (a, b) {return a - b});
  if (sum < 0) {
    result  = nums.join(' ')
  } else {
    nums.reverse()
    result = nums.join(' ')
  }
  if (result === str) {
    print('NO')
  } else {
    print('YES')
    print(result)
  }
}


var line = readline ();
line = line.trim ().split ( ' ' );
var n, m;
n = (+ line [ 0 ]);
m = (+ line [ 1 ]);
function gcd ( a, b ) {
    if ( b == 0 ) return a;
    else return gcd ( b, a % b );
}
var i, j;
var cnt = 0;
var graph = { };
l1: for ( i = 1; i <= n - 1; i ++ ) {
    l2: for ( j = i + 1; j <= n; j ++ ) {
        if ( gcd ( i, j ) == 1 ) {
            if ( ! ( i in graph ) ) graph [ i ] = { };
            graph [ i ][ j ] = 1;
            cnt ++;
        }
        if ( cnt >= m ) break l1;
    }
}
if ( cnt < m || m < (n - 1) ) {
    print ( 'Impossible' );
} else {
    var v, u;
    print ( 'Possible' );
    for ( v in graph )
        for ( u in graph [ v ] )
            print ( v + ' ' + u );
}

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  const container = [];
  for (let i = 1; i < n && container.length < m; i += 1) {
    for (let j = i + 1; j <= n && container.length < m; j += 1) {
      if (gcd(i, j) === 1) {
        container.push([i, j]);
      }
    }
  }

  if (m !== container.length || m < n - 1) {
    console.log('Impossible');
  } else {
    console.log('Possible');
    container.forEach((item) => {
      console.log(item.join(' '));
    });
  }
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  let edges = 0;
  const container = [];
  for (let i = 1; i < n && edges < m; i += 1) {
    for (let j = i + 1; j <= n && edges < m; j += i) {
      if (gcd(i, j) === 1) {
        container.push([i, j]);
        edges += 1;
      }
    }
  }

  if (m > edges || m < n - 1) {
    console.log('Impossible');
  } else {
    console.log('Possible');
    container.forEach((item) => {
      console.log(item.join(' '));
    });
  }
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  let edges = 0;
  const container = [];
  for (let i = 1; i < n && edges < m; i += 1) {
    for (let j = i + 1; j <= n && edges < m; j += i) {
      if (gcd(i, j) === 1) {
        container.push([i, j]);
        edges += 1;
      }
    }
  }

  if (m !== edges || m < n - 1) {
    console.log('Impossible');
  } else {
    console.log('Possible');
    container.forEach((item) => {
      console.log(item.join(' '));
    });
  }
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);

  const LIMIT = parseInt(n + 1, 10);
  const eulerPhi = new Array(LIMIT);
  for (let i = 0; i < LIMIT; i += 1)
    eulerPhi[i] = i;
  for (let i = 2; i < LIMIT; i += 1) {
    if (eulerPhi[i] === i) {
      for (let j = i; j < LIMIT; j += i)
        eulerPhi[j] -= parseInt(eulerPhi[j] / i);
    }
  }

  let edges = 0;
  for (let i = 2; i < LIMIT; i += 1) {
    edges += eulerPhi[i];
  }

  if (m > edges) {
    console.log('Impossible');
  } else {
    console.log('Possible');

    edges = 0;
    for (let i = 2; i < LIMIT && edges < m; i += 1) {
      console.log(`${1} ${i}`);
      edges += 1;
    }

    const primes = [];
    const compose = [];
    const sieve = new Array(LIMIT).fill(true);
    for (let i = 2; i < LIMIT; i += 1) {
      if (sieve[i]) {
        primes.push(i);
        for (let j = i * i; j < LIMIT; j += i) {
          sieve[j] = false;
        }
      } else {
        compose.push(i);
      }
    }

    primes.forEach((item) => {
      for (let i = item - 1; i > 1 && edges < m; i -= 1) {
        console.log(`${item} ${i}`);
        edges += 1;
      }
      for (let i = lowerBound(compose, item); i < compose.length && edges < m; i += 1) {
        if (compose[i] % item !== 0) {
          console.log(`${item} ${compose[i]}`);
          edges += 1;
        }
      }
    });
  }
}

function lowerBound(array, value) {
  let left = 0, middle;
  let right = array.length;
  while (left < right) {
    middle = parseInt((left + right) / 2);
    if (value <= array[middle])
      right = middle;
    else
      left = middle + 1;
  }

  return left; // not found
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  let edges = 0;
  const container = [];
  for (let i = 1; i < n && edges < m; i += 1) {
    for (let j = i + 1; j <= n && edges < m; j += i) {
      if (gcd(i, j) === 1) {
        container.push([i, j]);
        edges += 1;
      }
    }
  }

  if (m === edges || m < n - 1) {
    console.log('Impossible');
  } else {
    console.log('Possible');
    container.forEach((item) => {
      console.log(item.join(' '));
    });
  }
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  let edges = 0;
  const container = [];
  for (let i = 1; i < n && edges < m; i += 1) {
    for (let j = i + 1; j <= n && edges < m; j += i) {
      if (gcd(i, j) === 1) {
        container.push([i, j]);
        edges += 1;
      }
    }
  }

  if (m > edges) {
    console.log('Impossible');
  } else {
    console.log('Possible');
    container.forEach((item) => {
      console.log(item.join(' '));
    });
  }
}

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });


print(function(n,m){
	var a=readNumber().sort(function(a,b){return a-b;});
	var b=readNumber().sort(function(a,b){return a-b;});
	var ans=Math.max( a[0]*2, a[a.length-1] );
	if(b[0]<=ans) return -1;
	return ans;
}.apply(0, readNumber()));
function readNumber(){ return readline().split(' ').map(Number); }

;(function () {

	readline();
	var a = readline().split(' ').map(Number);
	var b = readline().split(' ').map(Number);

	var r = Math.max.apply(null, a);
	t = Math.max( 2 * Math.min.apply(null, a), r );

	if (r <= t && Math.min.apply(null, b) > t) print(t);
	else print(-1);

}).call(this);

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		goodNum = data[0], badNum = data[1],
		good = tokenizeIntegers(readline()),
		bad = tokenizeIntegers(readline());
	function sorter(a, b) {
		return a-b;
	}
	good.sort(sorter);
	bad.sort(sorter);
	var min = Math.max(good[good.length-1], 2*good[0]), max = bad[0]-1;
	print (min <= max ? min : -1);
}

main();

var n = readline().split(' ').map(Number);
var n_s = readline().split(' ').map(Number);
var m_s = readline().split(' ').map(Number);
var n_mi = Math.min.apply(null, n_s);
var n_mx = Math.max.apply(null, n_s);
var m_mi = Math.min.apply(null, m_s);
var ans = -1;
var mx = Math.max(n_mi * 2, n_mx);
if (mx < m_mi) ans = mx;
print(ans);

var n = readline().split(' ').map(Number);
var n_s = readline().split(' ').map(Number);
var m_s = readline().split(' ').map(Number);
var n_mi = Math.min.apply(null, n_s);
var n_mx = Math.max.apply(null, n_s);
var m_mi = Math.min.apply(null, m_s);
var ans = -1;
for (var i = n_mx; i < m_mi; i++) {
    if (i >= n_mi * 2) {
        ans = i;
        break;
    }
}
print(ans);

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() {
  const _ = readLine();
  const rightCases = readLine().split(" ").map(Number);
  const wrongCases = readLine().split(" ").map(Number);

  const [rightMin, rightMax, wrongMin] = [Math.min(...rightCases), Math.max(...rightCases), Math.min(...wrongCases)];

  const tl = rightMax >= rightMin * 2 ? rightMax : rightMin * 2;

  if (tl >= wrongMin) console.log(-1);
  else console.log(tl);
}

print(function(n,m){
	var a=readNumber().sort(function(a,b){return a-b;});
	var b=readNumber().sort(function(a,b){return a-b;});
	var ans=a[a.length-1];
	if(a[0]*2>ans) return -1;
	if(b[0]<=ans) return -1;
	return ans;
}.apply(0, readNumber()));
function readNumber(){ return readline().split(' ').map(Number); }

;(function () {

	readline();
	var a = readline().split(' ').map(Number);
	var b = readline().split(' ').map(Number);

	t = Math.max.apply(null, a);

	if (2 * Math.min.apply(null, a) <= t && Math.min.apply(null, b) > t) print(t);
	else print(-1);

}).call(this);

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

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

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

function main() {
	var numDigits = parseInt(readline()),
		digits = tokenizeIntegers(readline()),
		counts = { 0: 0, 5: 0 };
	for (var i = 0; i < numDigits; ++i) {
		counts[digits[i]] += 1;
	}
	if (counts[0] == 0) {
		print(-1);
		return;
	}
	if (counts[5] < 9) {
		print(0);
		return;
	}
	digits.sort(function (a, b) {
		return b-a;
	});
	for (var i = counts[5]%9; i != 0; --i) {
		digits.shift();
	}
	print(digits.join(''));
}

main();

var n = readline().split(' ').map(Number);
var n_s = readline().split(' ').map(Number);
var m_s = readline().split(' ').map(Number);
var n_mi = Math.min.apply(null, n_s);
var n_mx = Math.max.apply(null, n_s);
var m_mi = Math.max.apply(null, m_s);
var ans = -1;
for (var i = n_mx; i < m_mi; i++) {
    if (i >= n_mi * 2) {
        ans = i;
        break;
    }
}
print(ans);

var n = readline().split(' ').map(Number);
var n_s = readline().split(' ').map(Number);
var m_s = readline().split(' ').map(Number);
var n_mi = Math.min.apply(null, n_s);
var n_mx = Math.max.apply(null, n_s);
var m_mi = Math.max.apply(null, m_s);
var ans = -1;
for (var i = n_mi * 2; i < m_mi; i++) {
    if (i + 1 >= n_mx) {
        ans = i + 1;
        break;
    }
}
print(ans);

var n = readline().split(' ').map(Number);
var n_s = readline().split(' ').map(Number);
var m_s = readline().split(' ').map(Number);
var n_mi = Math.min.apply(null, n_s);
var n_mx = Math.max.apply(null, n_s);
var m_mi = Math.max.apply(null, m_s);
var ans = -1;
for (var i = n_mx; i < m_mi; i++) {
    if (i / 2 >= n_mi) {
        ans = i;
        break;
    }
}
print(ans);


var len = +readline(),
    directions = readline().split(""),
    distantions = readline().split(" ").map(i => parseInt(i)),
    map = [];

for (var i = 0; i < len; ++i) {
    map[i] = distantions[i] * (directions[i] == "<" ? -1 : 1);
}

var current = 0, iteration = 0, maxIterations = len, point;

while (iteration <= maxIterations && current >= 0 && current < len) {
    point = map[current];
    current += point;
    iteration++;
}

print(current < 0 || current >= len ? "FINITE" : "INFINITE");

var n = +readline()
  , actions = readline()
  , powers = readline().split(' ')
  , current_index = 0
  , path = [];

function calc() {
  var action
    , power;

  while(path[current_index] === undefined)
  {
    path[current_index] = 1;
    action = actions[current_index];
    power = +powers[current_index];
    if (action == '>') {
      current_index += power;
      if (current_index >= n) {
        return 'FINITE';
      }
    }

    if (action == '<') {
      current_index -= power;
      if (current_index < 0) {
        return 'FINITE';
      }
    }
  }
  if (current_index >=0 && current_index < n) {
    return 'INFINITE';
  }
  else {
    return 'FINITE';
  }
}
print(calc())

var n = +readline()
  , actions = readline()
  , powers = readline().split(' ')
  , current_index = 0
  , path = [];

function calc() {
  var action
    , power;

  while(path[current_index] === undefined)
  {
    path[current_index] = 1;
    action = actions[current_index];
    power = +powers[current_index];
    if (action == '>') {
      current_index += power;
      if (current_index > n) {
        return 'FINITE';
      }
    }

    if (action == '<') {
      current_index -= power;
      if (current_index < 0) {
        return 'FINITE';
      }
    }
  }
  if (current_index > 0 && current_index < n) {
    return 'INFINITE';
  }
  else {
    return 'FINITE';
  }
}
//console.log(result);
//console.log(calc())
print(calc())


function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => gt[n] * rgt[k] * rgt[n - k] % MOD;
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

// let p = [2, 3, 5];
// for (let i = 6; i < 1e5; i += 6) {
//   let j, x = i + 1;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
//   x = i + 5;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $(), n2 = n ** 0.5 | 0;
    if (n2 * n2 >= n) log(n2 + n2 - 2);
    else if (n2 * (n2 + 1) >= n) log(n2 + n2 - 1);
    else log(n2 + n2);
  }
}

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 n = +readLine();
    const sqrt = Math.floor(Math.sqrt(n));
    let p = Math.floor(n / sqrt);
    if (n % sqrt === 0) p--;
    const ans = p + sqrt - 1;

    console.log(ans);
  }
}

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 n = +readLine();
    let [flag, carry, count, ans] = [1, 1, 1, 0];
    while (count < n) {
      if (flag) {
        count += carry;
      } else {
        carry++;
        count += carry;
      }
      flag ^= 1;
      ans++;
    }

    console.log(ans);
  }
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var now = 1;
    var count = 1000000000;
    while(true){
      var nokori = N - now;
      var newCount = Math.ceil(nokori / now);
      if(count < newCount + now){
        break;
      }
      count = newCount + now;
      now++;
    }
    output[i] = count - 1;
  }
  myout(myconv(output, 9));
}

'use strict'
function mlt() { return readline().split(' ').map(x => parseInt(x)); }
function inp() { return parseInt(readline()) }
function solv() {
    var x = inp();
    var res = x;
    for (var n = 1; n * n <= x; n++) {
        var cur = n;
        var ans = n - 1;
        var more = Math.ceil((x - cur) / cur);
        ans += more;
        res = Math.min(res, ans);
    }
    print(res)
}

var tc = parseInt(readline())
while (tc--) solv()

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var n = int(readline())
        print(Math.ceil(2 * Math.sqrt(n)) - 2)
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

 while(t--)
         {

         var n,i;

           n=int(readline())

            if(n==1)print(0);

            else if(n==2)print(1);

            else{

                var ans=0;

                var a=Math.floor(Math.sqrt(n));

                ans=a-1;

                n-=a;

                ans+=Math.floor((n/a));

                if(n%a)ans++;

               print(ans);
            }

         }

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var n = int(readline())
        print(2 * Math.sqrt(n) - 2)
}


'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  let rl = 0,
      rr = 0,
      res = 0;
  for (let l = 0, r = n - 1; l <= r;) {
    if (rl <= rr) {
      rl += a[l++];
    } else {
      rr += a[r--];
    }
    if (rl === rr) {
      res = Math.max(res, l + n - r - 1);
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    let n = Number(await read()),
        a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

const readline = require('readline');

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

const lines = [];
rl.on('line', (input) => {
	lines.push(input);
});

rl.on('close', () => {
	// (function() {
	// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
	let l = 0;
	let t = +lines[l++];
	const output = [];
	for (let i = 0; i < t; i++) {
		const n = +lines[l++];
		const arr = lines[l++].trim().split(' ').map(Number);
		output[i] = solve(n, arr);
	}
	console.log(output.join('\n'));
	// })()
});

function solve(n, arr) {
	let alice_index = 0;
	let bob_index = arr.length - 1;
	let bob = (alice = ans = 0);
	while (alice_index <= bob_index) {
		if (alice <= bob) alice += arr[alice_index++];
		else bob += arr[bob_index--];

		if (alice == bob) ans = alice_index + arr.length - 1 - bob_index;
	}
	console.log(ans);
}

const solve = arr=>{
     let max = -1,alice = arr[0],bob = arr[arr.length-1],i=1,j = arr.length-1;
     while((i<=j)){
          if(alice===bob) max = (arr.length-j)+i;
          if(alice<=bob) alice+=arr[i++];
          else bob+=arr[--j];
     }
     if(max===-1) return 0;
     return max;
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(arr));
  }
}
main();

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = Number(lines[i]);
        }else{
            var ar = lines[i].split(' ').map(Number);
            var a = 0, b = n - 1;
            var a1 = ar[0], b1 = ar[b];
            var ans = 0;
            while(a < b){
                if(a1 == b1){
                    ans = a + 1 + n - b;
                    a++;
                    a1 += ar[a];
                }else if(a1 > b1){
                    b--;
                    b1 += ar[b];
                }else if(a1 < b1){
                    a++;
                    a1 += ar[a];
                }
            }
            console.log(ans);
        }
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

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

function main() {
    const T = readline();
    for (let i = 0; i < T; i++) {
        const n = readline()
        const A = readline().split(' ').map(x => +x)
        solve(A)
    }
}
function solve(A) {
    const wl = new Map()
    let sl = 0
    for (let i = 0; i < A.length; i++) {
        sl += A[i]
        wl.set(sl, i)
    }

    let max = 0
    let sr = 0
    for (let j = A.length - 1; j >= 0; j--) {
        sr += A[j]
        if (wl.has(sr) && wl.get(sr) < j) {
            max = Math.max(max, wl.get(sr) + 1 + A.length - j)
        }
    }

    console.log(max)
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', (_) => {
  inputString = inputString
    .trim()
    .split('\n')
    .map((string) => {
      return string.trim();
    });

  main();
});

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

function main() {
  let _t = parseInt(readline());
  while (_t) {
    _t--;
    let n = parseInt(readline());
    let a = [];
    a = readline()
      .split(' ')
      .map((e) => parseInt(e));
    let left = 0,
      right = n - 1,
      leftSum = 0,
      rightSum = 0,
      ans = 0;
    while (left <= right) {
      if (leftSum < rightSum) {
        leftSum += a[left++];
      } else {
        rightSum += a[right--];
      }
      if (rightSum === leftSum) ans = Math.max(ans, left + n - right - 1);
    }
    console.log(ans);
  }
}
// cat input.txt | node main.js

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

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

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

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

		const mp = [];
		for (let i = 0, sum = 0; i < n; i++) {
			sum += w[i];
			mp[sum] = i + 1;
		}

		let ans = 0;
		for (let i = n - 1, sum = 0; i >= 0; i--) {
			sum += w[i];
			if (mp[sum] && mp[sum] + n - i <= n) {
				ans = Math.max(ans, mp[sum] + n - i)
			}
		}

		console.log(ans);
	}
}

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

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

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

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

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

    let suma = 0;
    let sumb = 0;

    let l = -1;
    let r = n - 1;

    while (l < r) {
        suma += a[++l];

        while (l < r && sumb < suma) {
            sumb += a[r--];
        }

        if (suma === sumb) {
            result = Math.max(result, l + (n - r));
        }
    }

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    let i = -1
    let j = n
    let a = 0
    let b = 0
    let ans = 0
    let temp = 0
    while (i < j) {
        if (a < b) {
            a += arr[++i]
            temp++
        } else if (a > b) {
            b += arr[--j]
            temp++
        } else {
            ans += temp
            temp = 0
            if (i + 1 >= j - 1) break
            a += arr[++i]
            b += arr[--j]
            temp = 2
        }
        // console.log(a, b, temp)
    }
    if (a === b) ans += temp
    return ans
}

//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 if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
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();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = 0;
		var sum = new Array(N + 1);
		sum[0] = 0;
		for(var i = 1; i <= N; i++){
			sum[i] = sum[i - 1] + list[i - 1];
		}
		var right = 0;
		var V = 0;
		for(var i = N - 1; i >= 0; i--){
			right += list[i];
			V++;
			var L = 0;
			var R = i + 1;
			var ok = false;
			while(R - L > 1){
				var C = Math.floor((R + L) / 2);
				if(sum[C] > right){
					R = C;
				}else if(sum[C] < right){
					L = C;
				}else{
					L = C;
					ok = true;
					break;
				}
			}
			if(ok){
				output = Math.max(output, L + V);
			}
		}
		myout(output);
	}
}

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

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

const calc = (n, A)=>{
  let ans = 0;
  let l = 0, ls = A[l]
  let r = n-1, rs = A[r];
  while (l<r){
    if (ls==rs){
      ans = l+1+(n-r);
    }
    if (ls<rs){
      l++;
      ls += A[l]
    } else {
      r--;
      rs += A[r];
    }
  }
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = ra();
      L('Ans:')
      print(calc(n, A));
    }
}

E.calc = calc;

const readline = require('readline');

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

const lines = [];
rl.on('line', (input) => {
	lines.push(input);
});

rl.on('close', () => {
	// (function() {
	// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
	let l = 0;
	let t = +lines[l++];
	const output = [];
	for (let i = 0; i < t; i++) {
		const n = +lines[l++];
		const arr = lines[l++].trim().split(' ').map(parseInt);
		output[i] = solve(n, arr);
	}
	console.log(output.join('\n'));
	// })()
});

function solve(n, arr) {
	let alice_index = 0;
	let bob_index = arr.length - 1;
	let bob = (alice = ans = 0);
	while (alice_index <= bob_index) {
		if (alice <= bob) alice += arr[alice_index++];
		else bob += arr[bob_index--];

		if (alice == bob) ans = alice_index + arr.length - 1 - bob_index;
	}
	return ans;
}

'use strict';

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

const lines = [];
readline.on('line', (input) => {
    lines.push(input);
});

readline.on('close', () => {
    let lineIndex = 0;
    let repeat = +lines[lineIndex++];

    while (repeat--) {
        const candiesAmount = +lines[lineIndex++];
        const candies = lines[lineIndex++].trim().split(' ').map(parseInt);
        solve(candiesAmount, candies)
    }

});

function solve(len, candies) {
    let aliceIndex  = 0,
        bobIndex    = len - 1,
        alice       = 0,
        bob         = 0,
        ans         = 0;

    while (aliceIndex <= bobIndex) {

        if (alice <= bob) {
            alice += candies[aliceIndex];
            ++aliceIndex;
        }
        else {
            bob += candies[bobIndex];
            --bobIndex;
        }

        if (alice == bob) ans = aliceIndex + 1 + len - bobIndex;
    }

    console.log(ans);
}

const solve = arr=>{
     let max = -1,alice = arr[0],bob = arr[arr.length-1],i=1,j = arr.length-1;
     while((i<=j)){
          if(alice===bob) max = (arr.length-j)+i;
          if(arr.length-i-j===0){
               if(alice<=bob) alice+=arr[i++];
               else bob+=arr[--j];
          }
          else{
               if(i>arr.length-j) bob+=arr[--j];
               else alice+=arr[i++];
          }
     }
     if(max===-1) return 0;
     return max;
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(arr));
  }
}
main();