There is an infinite set generated as follows:  $$$1$$$ is in this set.  If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are:  $$$1$$$,  $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set),  $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set),  $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set),  $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) — the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.

For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, $$$24$$$ is generated as follows:  $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set;  $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set;  $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.

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

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

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
}

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


Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

  var tmp = readline().split(' ').map(x => parseInt(x));
  var n = tmp[0];
  var m = tmp[1] - 1;
  var k = tmp[2];
  var h = readline().split(' ').map(x => parseInt(x)).sort((a, b) => a - b);
  var find = (arr, e) => {
    var l = 0;
    var r = arr.length - 1;
    while (l <= r) {
      var m = ((l + r) / 2) | 0;
      if(arr[m] < e) {
        l = m + 1;
      } else if(arr[m] > e) {
        r = m - 1;
      } else {
        return m;
      }
    }
    return -1;
  }

  var cur = 1;
  var done = false;
  if(find(h, 1) !== -1) {
    done = true;
  }
  for(var i = 0; !done && i < k; i += 1) {
    var op = readline().split(' ').map(x => parseInt(x));
    if(op[0] === cur) {
      cur = op[1];
      if(find(h, cur) !== -1) {
        done = true;
      }
    } else if(op[1] === cur) {
      cur = op[0];
      if(find(h, cur) !== -1) {
        done = true;
      }
    }
  }
  print(cur);


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.

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

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

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)

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


Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.

If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.

NoteHere is the representation of the graph from the first example:

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


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

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

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


Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.  Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.

Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).

NoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is 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 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';
  }
}
//console.log(result);
//console.log(calc())
print(calc())


Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things:  Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one);  Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves:  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$.  You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$.  You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$.  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$.  You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the lower bound on the sum of the array.

For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.

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

         }

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

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

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

var t = int(readline())

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