package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1295D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	calcGCD := func(a, b int64) int64 {
		for b != 0 {
			a, b = b, a%b
		}
		return a
	}
	calcPhi := func(n int64) int64 {
		ans := n
		for i := int64(2); i*i <= n; i++ {
			if n%i == 0 {
				ans = ans / i * (i - 1)
				for ; n%i == 0; n /= i {
				}
			}
		}
		if n > 1 {
			ans = ans / n * (n - 1)
		}
		return ans
	}

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var a, m int64
		Fscan(in, &a, &m)
		Fprintln(out, calcPhi(m/calcGCD(a, m)))
	}
}

func main() {
	CF1295D(os.Stdin, os.Stdout)
}

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	_, q := a/d, m/d

	memo := TrialDivision(q)

	// ans := q
	// for e := range memo {
	// 	y := e - (p % e)
	// 	if y <= q-1 {
	// 		n := (q - y - 1) / e
	// 		num := maxll(n+1, 0)
	// 		ans -= num
	// 	}
	// }

	// オイラー関数を使ってみる
	ans := EulerPhi(q, memo)

	printf("%d\n", ans)
}

func EulerPhi(n int64, P map[int64]int64) int64 {
	res := n

	for p := range P {
		res /= p
		res *= (p - 1)
	}

	return res
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

/*******************************************************************/

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// minint returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// minll returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// maxint returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// maxll returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmini accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmini(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chminll accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chminll(updatedValue *int64, target int64) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxi accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"sync"
)
const maxn int = 1e7 + 1
var pri, mu, vis [maxn]int
var cnt int
func Init(n int) {
	mu[1] = 1
	for i := 2; i <= n; i++ {
		if vis[i] == 0 {
			cnt++
			pri[cnt] = i
			mu[i] = -1
		}
		for j := 1; j <= cnt && pri[j] * i <= n; j++ {
			vis[pri[j] * i] = 1
			if i % pri[j] != 0 {
				mu[i * pri[j]] = -mu[i]
			} else {
				break
			}
		}
	}
}
func GetPhi(n int64) int64 {
	m := n
	for j := int64(2); j * j <= m; j++ {
		if m % j == 0 {
			n = n / j * (j - 1)
			for ; m % j == 0; {
				m /= j
			}
		}
	}
	if m != 1 {
		n = n / m * (m - 1)
	}
	return n
}
func GetMu(n int64) int64 {
	cat := 0
	for j := int64(2); j * j <= n; j++ {
		if n % j == 0 {
			cat++
			sum := 0
			for ; n % j == 0; {
				n /= j
				sum++
			}
			if sum > 1 {
				return 0
			}
		}
	}
	if n > 1 {
		cat++
	}
	if cat % 2 == 1 {
		return -1
	} else {
		return 1
	}
}
func __gcd(a, b int64) int64 {
	if a % b == 0 {
		return b
	}
	return __gcd(b, a % b)
}
func solve() {
	n, m := ReadInt(), ReadInt()
	//fmt.Println(n)
	gcd := int64(__gcd(n, m))
	n /= gcd
	m /= gcd
	ans := GetPhi(m)
	fmt.Println(ans)
}
func main() {
	Init(1e7)
	for T := ReadInt(); T > 0; T-- {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup
func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int64 {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 64)
	return int64(i)
}
func ReadIntSlice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}

package main

import (
	"fmt"
)

func GetPrimeList(n int) []int {
	vis := make([]bool, n)
	primeList := []int{}

	for i := 2; i < n; i++ {
		if !vis[i] {
			primeList = append(primeList, i)
			for j := 2 * i; j < n; j += i {
				vis[j] = true
			}
		}
	}

	return primeList
}

func Gcd(a int64, b int64) int64 {
	if a == 0 {
		return b
	}
	return Gcd(b % a, a)
}

const (
	MAXN = 100005
)

func solve(primeList []int64, m int64) int64 {
	var ans int64
	n := len(primeList)
	for mask := 0; mask < (1 << uint(n)); mask++ {
		cur := int64(1)
		sgn := int64(1)
		for idx, val := range primeList {
			if (mask >> uint(idx) & 1) == 1 {
				cur *= val
				sgn = -sgn
			}
		}
		ans += sgn * (m / cur)
	}
	return ans
}

func main() {
	primeList := GetPrimeList(MAXN)

	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var a, m int64
		fmt.Scan(&a, &m)

		g := Gcd(a, m)
		mDivG := m / g

		curPrimeList := []int64{}
		for _, pri := range primeList {
			if mDivG % int64(pri) == 0 {
				curPrimeList = append(curPrimeList, int64(pri))
				for mDivG % int64(pri) == 0 {
					mDivG /= int64(pri)
				}
			}
		}
		if mDivG != 1 {
			curPrimeList = append(curPrimeList, mDivG)
		}
		fmt.Println(solve(curPrimeList, (a + m - 1) / g) - solve(curPrimeList, (a - 1) / g))
	}
}

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	p, q := a/d, m/d

	memo := TrialDivision(q)

	ans := q
	for e := range memo {
		y := e - (p % e)
		if y <= q-1 {
			n := (q - y - 1) / e
			num := maxll(n+1, 0)
			ans -= num
		}
	}

	printf("%d\n", ans)
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

/*******************************************************************/

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// minint returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// minll returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// maxint returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// maxll returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmini accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmini(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chminll accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chminll(updatedValue *int64, target int64) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxi accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*
URL:
https://codeforces.com/contest/1295/problem/D
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

var (
	t int

	a, m int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		a, m = readll2()

		solve()
	}
}

func solve() {
	d := Gcd(a, m)
	p, q := a/d, m/d

	memo := TrialDivision(q)

	ans := q
	for e := range memo {
		y := e - (p % e)
		n := (q - y - 1) / e

		num := maxll(n+1, 0)
		ans -= num
	}

	printf("%d\n", ans)
}

// TrialDivision returns the result of prime factorization of integer N.
func TrialDivision(n int64) map[int64]int64 {
	var i, exp int64
	p := map[int64]int64{}

	if n <= 1 {
		panic(errors.New("[argument error]: TrialDivision only accepts a NATURAL number"))
	}

	for i = 2; i*i <= n; i++ {
		exp = 0
		for n%i == 0 {
			exp++
			n /= i
		}

		if exp == 0 {
			continue
		}
		p[i] = exp
	}
	if n > 1 {
		p[n] = 1
	}

	return p
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int64) int64 {
	if a < 0 || b < 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int64) int64 {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

/*******************************************************************/

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// modi can calculate a right residual whether value is positive or negative.
func modi(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// modll can calculate a right residual whether value is positive or negative.
func modll(val, m int64) int64 {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// minint returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// minll returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func minll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// maxint returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxint(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// maxll returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func maxll(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmini accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmini(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chminll accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chminll(updatedValue *int64, target int64) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxi accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxi(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// chmaxll accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmaxll(updatedValue *int64, target int64) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}


package main

import (
	"fmt"
)

func main() {
	var q int
	fmt.Scan(&q)
	for t := 0; t < q; t++ {
		var n, m int
		fmt.Scan(&n, &m)
		matrix := make([][]int, n)
		for i, _ := range matrix {
			matrix[i] = make([]int, m)
			var s string
			fmt.Scan(&s)
			for j, v := range s {
				matrix[i][j] = int(v - '0')
			}
		}
		var continueCondition bool = true
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				if matrix[i][j]+matrix[i+1][j]+matrix[i][j+1]+matrix[i+1][j+1] == 3 {
					continueCondition = false
					break
				}
			}
			if !continueCondition {
				break
			}
		}
		if continueCondition {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscan(in, &n, &m)

		z := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &z[i])
		}

		var overlap bool
	Loop:
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				var c int
				for _, ch := range z[i][j : j+2] {
					if ch == '1' {
						c++
					}
				}

				for _, ch := range z[i+1][j : j+2] {
					if ch == '1' {
						c++
					}
				}

				if c == 3 {
					overlap = true
					break Loop
				}
			}
		}
		if !overlap {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	_r, _w := os.Stdin, os.Stdout
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var solve func()
	// Todo...
	solve = func() {
		var n, m int
		Fscan(in, &n, &m)
		rec := make([][]int, n+2)
		for i := 0; i < n+2; i++ {
			rec[i] = make([]int, m+2)
		}
		for i := 0; i < n+2; i++ {
			for j := 0; j < m+2; j++ {
				rec[i][j] = 1
			}
		}
		var s string
		for i := 1; i <= n; i++ {
			Fscan(in, &s)
			for j := 1; j <= m; j++ {
				if s[j-1] == '1' {
					rec[i][j] = 1
				} else {
					rec[i][j] = 0
				}
			}
		}
		ok := true
		for i := 1; i <= n; i++ {
			for j := 2; j <= m; j++ {
				if rec[i][j] == 0 {
					continue
				}
				if rec[i][j] == rec[i][j-1] && rec[i+1][j] != rec[i+1][j-1] {
					ok = false
				}
				if rec[i][j] == rec[i][j-1] && rec[i-1][j] != rec[i-1][j-1] {
					ok = false
				}
			}
		}
		if ok {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
	// End...
	var T int = 1
	Fscan(in, &T)
	for i := 0; i < T; i++ {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, m int
		fmt.Fscan(r, &n, &m)

		mat := make([][]byte, n)
		for i := range mat { fmt.Fscan(r, &mat[i]) }

		res := "YES"
		for i := 1; i < n; i++ {
			for j := 1; j < m; j++ {
				if mat[i][j] == '1' && mat[i][j] == mat[i-1][j-1] && mat[i][j-1] != mat[i-1][j] { res = "NO" }
				if mat[i-1][j] == '1' && mat[i][j] != mat[i-1][j-1] && mat[i][j-1] == mat[i-1][j] { res = "NO" }
			}
		}

		fmt.Fprintln(w, res)
	}

}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

const (
	INF = 3e5 + 10
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var t int
	Fscan(in, &t)

	for k := 0; k < t; k++ {
		var n, m int

		Fscan(in, &n, &m)

		a := make([]string, n)

		for i := 0; i < n; i++ {
			Fscan(in, &a[i])
		}

		flag := true
		for i := 0; i < n && flag; i++ {
			for j := 0; j < m && flag; j++ {
				if a[i][j] == '0' {
					if i > 0 && j > 0 && a[i-1][j-1] == '1' && a[i][j-1] == '1' && a[i-1][j] == '1' {
						Fprintln(out, "NO")
						flag = false
						break
					}

					if i > 0 && j < m-1 && a[i-1][j] == '1' && a[i-1][j+1] == '1' && a[i][j+1] == '1' {
						Fprintln(out, "NO")
						flag = false
						break
					}

					if i < n-1 && j > 0 && a[i][j-1] == '1' && a[i+1][j-1] == '1' && a[i+1][j] == '1' {
						Fprintln(out, "NO")
						flag = false
						break
					}

					if i < n-1 && j < m-1 && a[i][j+1] == '1' && a[i+1][j+1] == '1' && a[i+1][j] == '1' {
						Fprintln(out, "NO")
						flag = false
						break
					}

				}
			}
		}
		if flag {
			Fprintln(out, "YES")
		}

	}

}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	for n > 0 {
		n--
		var a, b int
		fmt.Scan(&a, &b)
		x := make(map[int]string, a)
		var inp string
		for i := 0; i < a; i++ {
			fmt.Scan(&inp)
			x[i] = inp
		}
		var k int
	iForLoop:
		for i := 0; i < a-1; i++ {
			for j := 0; j < b-1; j++ {
				if (string(x[i][j]) == "1" && string(x[i][j+1]) == "1") || (string(x[i+1][j]) == "1" && string(x[i+1][j+1]) == "1") {
					k = 0
					if string(x[i][j]) == "1" {
						k++
					}
					if string(x[i][j+1]) == "1" {
						k++
					}
					if string(x[i+1][j]) == "1" {
						k++
					}
					if string(x[i+1][j+1]) == "1" {
						k++
					}
					if k == 3 {
						fmt.Println("NO")
						break iForLoop
					}
				}
			}
		}
		if k != 3 {
			fmt.Println("YES")
		}

	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		var n, m int
		var check bool = false
		fmt.Fscan(in, &n, &m)
		board := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &board[i])
		}
		if n == 1 || m == 1 {
			fmt.Println("YES")
			continue
		}
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				if board[i][j] == '1' && board[i][j+1] == '0' && board[i+1][j] == '1' && board[i+1][j+1] == '1' {
					check = true
					break
				}
				if board[i][j] == '0' && board[i][j+1] == '1' && board[i+1][j] == '1' && board[i+1][j+1] == '1' {
					check = true
					break
				}
				if board[i][j] == '1' && board[i][j+1] == '1' && board[i+1][j] == '0' && board[i+1][j+1] == '1' {
					check = true
					break
				}
				if board[i][j] == '1' && board[i][j+1] == '1' && board[i+1][j] == '1' && board[i+1][j+1] == '0' {
					check = true
					break
				}
			}
			if check {
				break
			}
		}
		if check {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
		}
	}

}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

/*

 */

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n, m int
	scanf("%d %d\n", &n, &m)

	tbl := make([]string, n)

	for i := range tbl {
		scanf("%s\n", &tbl[i])
	}

	for i := 0; i < n-1; i++ {
		for j := 0; j < m-1; j++ {
			cnt := 0
			if tbl[i][j] == '1' {
				cnt++
			}
			if tbl[i][j+1] == '1' {
				cnt++
			}
			if tbl[i+1][j] == '1' {
				cnt++
			}
			if tbl[i+1][j+1] == '1' {
				cnt++
			}

			if cnt == 3 {
				fmt.Fprintln(writer, "NO")
				return
			}
		}
	}

	fmt.Fprintln(writer, "YES")
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	idx := 0
	for i, num := range nums {
		if num > nums[idx] {
			idx = i
		}
	}

	return nums[idx]
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscan(in, &n, &m)

		var f bool
		table := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &table[i])
		}

		for i := 1; i < n; i++ {
			if table[i-1] == table[i] {
				continue
			}

			for j := 0; j < m; j++ {
				if table[i-1][j] != table[i][j] {
					if j == 0 && j+1 < m {
						if table[i-1][j+1] == '1' && table[i][j+1] == '1' {
							f = true
						}
					} else if j > 0 && table[i-1][j-1] == '1' && table[i][j-1] == '1' {
						f = true
					}
				}
			}
		}

		if !f {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscan(in, &n, &m)

		var s string
		fmt.Fscan(in, &s)
		z, _ := strconv.ParseInt(s, 2, 64)

		overlap := func(a, b int64) bool {
			for a > 0 && b > 0 {
				if a&b&1 > 0 {
					return true
				}
				a >>= 1
				b >>= 1
			}
			return false
		}

		var f bool
		for i := 1; i < n; i++ {
			fmt.Fscan(in, &s)

			d, _ := strconv.ParseInt(s, 2, 64)
			if z != d && overlap(z, d) {
				f = true
			}
			z = d
		}

		if !f {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscan(in, &n, &m)

		table := make([]string, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &table[i])
		}

		r := false
		for _, v := range table {
			f := true
			for _, ch := range v {
				if ch == '0' {
					f = false
					break
				}
			}

			if f {
				r = true
				break
			}
		}

		c := false
		for j := 0; j < m; j++ {
			f := true
			for i := 0; i < n; i++ {
				if table[i][j] == '0' {
					f = false
					break
				}
			}

			if f {
				c = true
				break
			}
		}

		if r && c {
			fmt.Fprintln(out, "NO")
		} else {
			fmt.Fprintln(out, "YES")
		}
	}
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	_r, _w := os.Stdin, os.Stdout
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var solve func()
	// Todo...
	solve = func() {
		var n, m int
		Fscan(in, &n, &m)
		rec := make([][]int, n+2)
		for i := 0; i < n+2; i++ {
			rec[i] = make([]int, m+2)
		}
		for i := 0; i < n+2; i++ {
			for j := 0; j < m+2; j++ {
				rec[i][j] = 1
			}
		}
		var s string
		for i := 1; i <= n; i++ {
			Fscan(in, &s)
			for j := 1; j <= m; j++ {
				if s[j-1] == '1' {
					rec[i][j] = 1
				} else {
					rec[i][j] = 0
				}
			}
		}
		ok := true
		for i := 1; i <= n; i++ {
			for j := 2; j <= m; j++ {
				if rec[i][j] == 0 {
					continue
				}
				if rec[i][j] == rec[i][j-1] && rec[i+1][j] != rec[i+1][j-1] {
					ok = false
				}
			}
		}
		if ok {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
	// End...
	var T int = 1
	Fscan(in, &T)
	for i := 0; i < T; i++ {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	_r, _w := os.Stdin, os.Stdout
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var solve func()
	// Todo...
	solve = func() {
		var n, m int
		Fscan(in, &n, &m)
		rec := make([][]int, n+2)
		for i := 0; i < n+2; i++ {
			rec[i] = make([]int, m+2)
		}
		for i := 0; i < n+2; i++ {
			for j := 0; j < m+2; j++ {
				rec[i][j] = 1
			}
		}
		var s string
		for i := 1; i <= n; i++ {
			Fscan(in, &s)
			for j := 1; j <= m; j++ {
				if s[j-1] == '1' {
					rec[i][j] = 1
				} else {
					rec[i][j] = 0
				}
			}
		}
		ok := true
		for i := 1; i <= n; i++ {
			for j := 2; j <= m; j++ {
				if rec[i][j] == rec[i][j-1] && rec[i+1][j] != rec[i+1][j-1] {
					ok = false
				}
			}
		}
		if ok {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
	// End...
	var T int = 1
	Fscan(in, &T)
	for i := 0; i < T; i++ {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	_r, _w := os.Stdin, os.Stdout
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var solve func()
	// Todo...
	solve = func() {
		var n, m int
		Fscan(in, &n, &m)
		rec := make([][]int, n+2)
		for i := 0; i < n+2; i++ {
			rec[i] = make([]int, m+2)
		}
		for i := 0; i < n+2; i++ {
			for j := 0; j < m+2; j++ {
				rec[i][j] = 1
			}
		}
		var s string
		for i := 1; i <= n; i++ {
			Fscan(in, &s)
			for j := 1; j <= m; j++ {
				if s[j-1] == '1' {
					rec[i][j] = 1
				} else {
					rec[i][j] = 0
				}
			}
		}
		ok := true
		for i := 1; i <= n; i++ {
			for j := 1; j <= m; j++ {
				if rec[i+1][j] == 1 && rec[i-1][j] == 1 && rec[i][j+1] == 1 && rec[i][j-1] == 1 {
					if (i == 1 && j == 1) || (i == n && j == m) || (i == n && j == 1) || (i == 1 && j == m) {
						continue
					}
					if n == 1 || m == 1 {
						continue
					}
					//Fprintln(out, i, j, "---")
					ok = false
				}
			}
		}
		if ok {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
	// End...
	var T int = 1
	Fscan(in, &T)
	for i := 0; i < T; i++ {
		solve()
	}
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}


package main
import "fmt"
import "os"
import "bufio"

var input *bufio.Reader

func max(a, b int) int {
    if a>b {
        return a
    }
    return b
}

func min(a, b int) int {
    if a<b {
        return a
    }
    return b
}

const MOD = 2520
const N = 1005

var m, k [N]int
var e [N][12]int
var ans [N][MOD]int
var pos [N][MOD]int
var vec [N*MOD]int
var vis [N]bool

func getmod(a int) int {
    return (a%MOD+MOD)%MOD
}

func getans(u, w, index int) int {
    w = getmod(w+k[u])
    if ans[u][w] != 0 {
        return ans[u][w]
    }
    pos[u][w] = index
    vec[index] = u
    v := e[u][w%m[u]]

    if ans[v][getmod(w+k[v])] != 0 {
        ans[u][w] = ans[v][getmod(w+k[v])]
    } else if pos[v][getmod(w+k[v])]!=0 {
        l := pos[v][getmod(w+k[v])]; r := index
        tans := 0
        for i:=l; i<=r; i++ {
            if !vis[vec[i]] {
                tans++
                vis[vec[i]] = true
            }
        }
        for i:=l; i<=r; i++ {
            vis[vec[i]] = false
        }
        ans[u][w] = tans
    } else {
        ans[u][w] = getans(v, w, index+1)
    }
    return ans[u][w]
}

func main(){
    input = bufio.NewReader(os.Stdin)

    var n int
    fmt.Fscanf(input, "%d\n", &n)
    for i:=1; i<=n; i++ {
        fmt.Fscanf(input, "%d", &k[i])
    }
    fmt.Fscanf(input, "\n")
    for i:=1; i<=n; i++ {
        fmt.Fscanf(input, "%d\n", &m[i])
        for j:=0; j<m[i]; j++ {
            fmt.Fscanf(input, "%d", &e[i][j])
        }
        fmt.Fscanf(input, "\n")
    }
    var Q int
    fmt.Fscanf(input, "%d\n", &Q)
    for i:=1; i<=Q; i++ {
        var x, y int
        fmt.Fscanf(input, "%d%d\n", &x, &y)
        //fmt.Printf("%d\n", getans(x, y, 1))
        fmt.Println(getans(x, y, 1))
    }
}

package main
import "fmt"
import "os"
import "bufio"

var input *bufio.Reader

func max(a, b int) int {
    if a>b {
        return a
    }
    return b
}

func min(a, b int) int {
    if a<b {
        return a
    }
    return b
}

const MOD = 2520
const N = 1005

var m, k [N]int
var e [N][12]int
var ans [N][MOD]int
var pos [N][MOD]int
var vec [N*MOD]int
var vis [N]bool

func getmod(a int) int {
    return (a%MOD+MOD)%MOD
}

func getans(u, w, index int) int {
    w = getmod(w+k[u])
    if ans[u][w] != 0 {
        return ans[u][w]
    }
    pos[u][w] = index
    vec[index] = u
    v := e[u][w%m[u]]

    if ans[v][getmod(w+k[v])] != 0 {
        ans[u][w] = ans[v][getmod(w+k[v])]
    } else if pos[v][getmod(w+k[v])]!=0 {
        l := pos[v][getmod(w+k[v])]; r := index
        tans := 0
        for i:=l; i<=r; i++ {
            if !vis[vec[i]] {
                tans++
                vis[vec[i]] = true
            }
        }
        for i:=l; i<=r; i++ {
            vis[vec[i]] = false
        }
        ans[u][w] = tans
    } else {
        ans[u][w] = getans(v, w, index+1)
    }
    return ans[u][w]
}

func main(){
    input = bufio.NewReader(os.Stdin)

    var n int
    fmt.Fscanf(input, "%d\n", &n)
    for i:=1; i<=n; i++ {
        fmt.Fscanf(input, "%d", &k[i])
    }
    fmt.Fscanf(input, "\n")
    for i:=1; i<=n; i++ {
        fmt.Fscanf(input, "%d\n", &m[i])
        for j:=0; j<m[i]; j++ {
            fmt.Fscanf(input, "%d", &e[i][j])
        }
        fmt.Fscanf(input, "\n")
    }
    var Q int
    fmt.Fscanf(input, "%d\n", &Q)
    for i:=1; i<=Q; i++ {
        var x, y int
        fmt.Fscanf(input, "%d%d\n", &x, &y)
        fmt.Printf("%d\n", getans(x, y, 1))
    }
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type colorer struct {
	black []string
	white []string
}

func NewColorer() *colorer {
	return &colorer{
		black: []string{},
		white: []string{},
	}
}

func (c *colorer) Color(s string, color bool) {
	if color {
		c.black = append(c.black, s)
	} else {
		c.white = append(c.white, s)
	}
}

func (c *colorer) GetShorter() []string {
	if len(c.black) <= len(c.white) {
		return c.black
	}
	return c.white
}

func sol(al map[string]map[string]bool) []string {
	visited := map[string]bool{}
	ret := []string{}
	for v, _ := range al {
		if visited[v] {
			continue
		}
		c := NewColorer()
		color := true
		toVisit := map[string]bool{v: true}
		for len(toVisit) > 0 {
			toVisitNext := map[string]bool{}
			for visiting, _ := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				c.Color(visiting, color)
				for visitNext, _ := range al[visiting] {
					if !visited[visitNext] {
						toVisitNext[visitNext] = true
					}
				}
			}
			toVisit = toVisitNext
			color = !color
		}
		ret = append(ret, c.GetShorter()...)
	}
	return ret
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	var read = bufio.NewReader(os.Stdin)
	var write = bufio.NewWriter(os.Stdout)
	var tn int
	fmt.Fscan(read, &tn)
	for t := 0; t < tn; t++ {
		//тесты
		var n, m int
		var n1, n2 int
		fmt.Fscan(read, &n, &m)
		var a = make([]int, n)
		for i := 0; i < m; i++ {
			var v, u int
			fmt.Fscan(read, &v, &u)
			v = v - 1
			u = u - 1
			if a[v] == 0 && a[u] == 0 {
				a[v] = 1
				a[u] = 2
				n1 = n1 + 1
				n2 = n2 + 1
			} else if a[v] == 0 && a[u] == 1 {
				a[v] = 2
				n2 = n2 + 1
			} else if a[v] == 0 && a[u] == 2 {
				a[v] = 1
				n1 = n1 + 1
			} else if a[v] == 1 && a[u] == 0 {
				a[u] = 2
				n2 = n2 + 1
			} else if a[v] == 2 && a[u] == 0 {
				a[u] = 1
				n1 = n1 + 1
			}
		}
		var r = n1
		var tr = 1
		if n2 < r {
			r = n2
			tr = 2
		}
		fmt.Fprintln(write, r)
		for i := 0; i < n; i++ {
			if a[i] == tr {
				fmt.Fprint(write, (i + 1), " ")
			}
		}
		fmt.Fprintln(write, "")

	}

	write.Flush()

}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type colorer struct {
	black []string
	white []string
}

func NewColorer() *colorer {
	return &colorer{
		black: []string{},
		white: []string{},
	}
}

func (c *colorer) Color(s string, color bool) {
	if color {
		c.black = append(c.black, s)
	} else {
		c.white = append(c.white, s)
	}
}

func (c *colorer) GetShorter() []string {
	if len(c.black) <= len(c.white) {
		return c.black
	}
	return c.white
}

func sol(al map[string]map[string]bool) []string {
	visited := map[string]bool{}
	c := NewColorer()
	color := true
	for v, _ := range al {
		if visited[v] {
			continue
		}
		toVisit := map[string]bool{v: true}
		for len(toVisit) > 0 {
			toVisitNext := map[string]bool{}
			for visiting, _ := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				c.Color(visiting, color)
				for visitNext, _ := range al[visiting] {
					if !visited[visitNext] {
						toVisitNext[visitNext] = true
					}
				}
			}
			toVisit = toVisitNext
			color = !color
		}
	}
	return c.GetShorter()
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type colorer struct {
	isBlack bool
	black   []string
	white   []string
}

func NewColorer() *colorer {
	return &colorer{
		isBlack: true,
		black:   []string{},
		white:   []string{},
	}
}

func (c *colorer) Color(s string) {
	if c.isBlack {
		c.black = append(c.black, s)
	} else {
		c.white = append(c.white, s)
	}
	c.isBlack = !c.isBlack
}

func (c *colorer) GetShorter() []string {
	if len(c.black) <= len(c.white) {
		return c.black
	}
	return c.white
}

func sol(al map[string]map[string]bool) []string {
	visited := map[string]bool{}
	ret := []string{}
	for k, _ := range al {
		if visited[k] {
			continue
		}
		c := NewColorer()
		toVisit := []string{k}
		for len(toVisit) > 0 {
			toVisitNext := []string{}
			for _, visiting := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				c.Color(visiting)
				for visitNext, _ := range al[visiting] {
					if !visited[visitNext] {
						toVisitNext = append(toVisitNext, visitNext)
					}
				}
			}
			toVisit = toVisitNext
		}
		ret = append(ret, c.GetShorter()...)
	}
	return ret
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type colorer struct {
	isBlack bool
	black   []string
	white   []string
}

func NewColorer() *colorer {
	return &colorer{
		isBlack: true,
		black:   []string{},
		white:   []string{},
	}
}

func (c *colorer) Color(s string) {
	if c.isBlack {
		c.black = append(c.black, s)
	} else {
		c.white = append(c.white, s)
	}
	c.isBlack = !c.isBlack
}

func (c *colorer) GetShorter() []string {
	if len(c.black) <= len(c.white) {
		return c.black
	}
	return c.white
}

func sol(al map[string]map[string]bool) []string {
	visited := map[string]bool{}
	ret := []string{}
	for v, _ := range al {
		if visited[v] {
			continue
		}
		c := NewColorer()
		toVisit := map[string]bool{v: true}
		for len(toVisit) > 0 {
			toVisitNext := map[string]bool{}
			for visiting, _ := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				c.Color(visiting)
				for visitNext, _ := range al[visiting] {
					if !visited[visitNext] {
						toVisitNext[visitNext] = true
					}
				}
			}
			toVisit = toVisitNext
		}
		ret = append(ret, c.GetShorter()...)
	}
	return ret
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func sol(al map[string]map[string]bool) []string {
	l := []string{}
	r := []string{}
	b := true
	visited := map[string]bool{}
	toVisit := []string{}
	for k, _ := range al {
		toVisit = append(toVisit, k)
	}
	for len(toVisit) > 0 {
		toVisitNext := []string{}
		for _, visiting := range toVisit {
			if visited[visiting] {
				continue
			}
			visited[visiting] = true
			if b {
				l = append(l, visiting)
			} else {
				r = append(r, visiting)
			}
			b = !b
			for visitNext, _ := range al[visiting] {
				if !visited[visitNext] {
					toVisitNext = append(toVisitNext, visitNext)
				}
			}
		}
		toVisit = toVisitNext
	}

	if len(l) <= len(r) {
		return l
	}
	return r
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type twoSlice struct {
	switcher bool
	slice1   []string
	slice2   []string
}

func NewTwoSlice() *twoSlice {
	return &twoSlice{
		switcher: true,
		slice1:   []string{},
		slice2:   []string{},
	}
}

func (ts *twoSlice) Add(s string) {
	if ts.switcher {
		ts.slice1 = append(ts.slice1, s)
	} else {
		ts.slice2 = append(ts.slice2, s)
	}
	ts.switcher = !ts.switcher
}

func (ts *twoSlice) GetRes() []string {
	if len(ts.slice1) <= len(ts.slice2) {
		return ts.slice1
	}
	return ts.slice2
}

func sol(al map[string]map[string]bool) []string {
	ts := NewTwoSlice()
	visited := map[string]bool{}
	toVisit := []string{}
	for k, _ := range al {
		toVisit = append(toVisit, k)
	}
	for len(toVisit) > 0 {
		toVisitNext := []string{}
		for _, visiting := range toVisit {
			if visited[visiting] {
				continue
			}
			visited[visiting] = true
			ts.Add(visiting)
			for visitNext, _ := range al[visiting] {
				if !visited[visitNext] {
					toVisitNext = append(toVisitNext, visitNext)
				}
			}
		}
		toVisit = toVisitNext
	}
	return ts.GetRes()
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func sol(al map[string]map[string]bool) []string {
	b := true
	l := []string{}
	r := []string{}
	visited := map[string]bool{}
	for k, _ := range al {
		if visited[k] {
			continue
		}
		toVisit := []string{k}
		for len(toVisit) > 0 {
			tmp := []string{}
			for _, visiting := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				if b {
					l = append(l, visiting)
				} else {
					r = append(r, visiting)
				}
				b = !b
				for v2, _ := range al[visiting] {
					if !visited[v2] {
						tmp = append(tmp, v2)
					}
				}
			}
			toVisit = tmp
		}
	}

	if len(l) <= len(r) {
		return l
	}
	return r
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func sol(al map[string]map[string]bool) []string {
	l := []string{}
	r := []string{}
	visited := map[string]bool{}
	for k, _ := range al {
		if visited[k] {
			continue
		}
		b := true
		toVisit := []string{k}
		for len(toVisit) > 0 {
			tmp := []string{}
			for _, visiting := range toVisit {
				if visited[visiting] {
					continue
				}
				visited[visiting] = true
				if b {
					l = append(l, visiting)
				} else {
					r = append(r, visiting)
				}
				b = !b
				for v2, _ := range al[visiting] {
					if !visited[v2] {
						tmp = append(tmp, v2)
					}
				}
			}
			toVisit = tmp
		}
	}

	if len(l) <= len(r) {
		return l
	}
	return r
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < t; i++ {
		al := map[string]map[string]bool{}
		scanner.Scan()
		nm := strings.Split(scanner.Text(), " ")
		m, _ := strconv.Atoi(nm[1])
		for j := 0; j < m; j++ {
			scanner.Scan()
			e := strings.Split(scanner.Text(), " ")
			l, r := e[0], e[1]
			if _, ok := al[l]; !ok {
				al[l] = map[string]bool{}
			}
			if _, ok := al[r]; !ok {
				al[r] = map[string]bool{}
			}
			al[l][r] = true
			al[r][l] = true
		}
		res := sol(al)
		fmt.Println(len(res))
		fmt.Println(strings.Join(res, " "))
	}
}


package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

type Node struct {
	Adj []int
	// The id of the previous node if this node is reachable by odd number of edges.
	// 0 means unknown.
	OddPrev  int
	EvenPrev int
}

const Unknown = 0

func main() {
	r := RapidReader()
	var n, m int
	for {
		if _, err := fmt.Fscan(r, &n, &m); err != nil {
			break
		}
		g := make([]Node, n+1)
		for x := 1; x <= n; x++ {
			var cnt int
			fmt.Fscan(r, &cnt)
			for j := 0; j < cnt; j++ {
				var y int
				fmt.Fscan(r, &y)
				g[x].Adj = append(g[x].Adj, y)
			}
		}
		var s int
		fmt.Fscan(r, &s)

		traversal(g, n, s)

		zeroOut := 0
		winEnd := Unknown
		for x := 1; x <= n; x++ {
			if len(g[x].Adj) == 0 {
				zeroOut++
				if g[x].OddPrev != Unknown {
					winEnd = x
					break
				}
			}
		}

		if winEnd != Unknown {
			fmt.Println("Win")
			var ans []int
			var walk func(int, bool)
			walk = func(x int, odd bool) {
				ans = append(ans, x)
				if odd && x != g[x].OddPrev {
					walk(g[x].OddPrev, false)
				} else if !odd && x != g[x].EvenPrev {
					walk(g[x].EvenPrev, true)
				}
			}
			walk(winEnd, true)
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Printf("%d ", ans[i])
			}
			fmt.Println()
			continue
		}

		if hasCircle(g, n, s) {
			fmt.Println("Draw")
		} else {
			fmt.Println("Lose")
		}
	}
}

func hasCircle(g []Node, n, s int) bool {
	rank := make([]int, n+1, n+1)
	yes := false
	var dfs func(int, int)
	dfs = func(x, r int) {
		rank[x] = r
		for _, y := range g[x].Adj {
			if rank[y] != 0 && rank[y] < r {
				yes = true
			}
			if rank[y] == 0 {
				dfs(y, r+1)
			}
		}
		rank[x] = 1000 * 1000
	}
	dfs(s, 1)
	return yes
}

func traversal(g []Node, n, s int) {
	g[s].EvenPrev = s
	stack := []int{s}

	for len(stack) > 0 {
		x := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		for _, y := range g[x].Adj {
			if g[x].OddPrev != Unknown && g[y].EvenPrev == Unknown {
				g[y].EvenPrev = x
				stack = append(stack, y)
			}
			if g[x].EvenPrev != Unknown && g[y].OddPrev == Unknown {
				g[y].OddPrev = x
				stack = append(stack, y)
			}
		}
	}
}

func RapidReader() io.Reader {
	b, _ := ioutil.ReadAll(os.Stdin)
	return bytes.NewReader(b)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var in = bufio.NewReaderSize(os.Stdin, 2<<16)

func readInt() int {
	var n int
	fmt.Fscan(in, &n)
	return n
}

func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	n := readInt()
	_ = readInt()
	edges := make([][]int, n)
	for i := range edges {
		for c := readInt(); c > 0; c-- {
			edges[i] = append(edges[i], readInt()-1)
		}
	}
	s := readInt() - 1
	type state struct {
		petya bool
		v     int
	}
	q := []state{{true, s}}
	parent := map[state]int{q[0]: 0}
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		if len(edges[v.v]) == 0 && !v.petya {
			var ans []int
			for v != (state{true, s}) {
				ans = append(ans, v.v)
				v.v = parent[v]
				v.petya = !v.petya
			}
			ans = append(ans, s)
			fmt.Fprintln(out, "Win")
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Fprint(out, ans[i]+1)
				if i == 0 {
					fmt.Fprintln(out)
				} else {
					fmt.Fprint(out, " ")
				}
			}
			return
		}
		for _, u := range edges[v.v] {
			uu := state{!v.petya, u}
			if _, has := parent[uu]; has {
				continue
			}
			parent[uu] = v.v
			q = append(q, uu)
		}
	}

	inStack := make([]bool, n)
	visited := make([]bool, n)
	var dfs func(int)
	dfs = func(v int) {
		visited[v] = true
		inStack[v] = true
		for _, u := range edges[v] {
			if !visited[u] {
				dfs(u)
			} else if inStack[u] {
				fmt.Println("Draw")
				os.Exit(0)
			}
		}
		inStack[v] = false
	}
	dfs(s)

	fmt.Println("Lose")
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var n, m int
var start int
var graph [][]int
var used [][2]bool
var nodes map[int]bool
var path []int

func dfs(v, t int) {
	path = append(path, v)
	if len(graph[v]) == 0 && t == 1 {
		fmt.Println("Win")
		for _, v := range path {
			fmt.Printf("%d ", v+1)
		}
		os.Exit(0)
	}
	used[v][t] = true
	for _, vnext := range graph[v] {
		if !used[vnext][1 - t] {
			dfs(vnext, 1 - t)
		}
	}
	path = path[:len(path) - 1]
}

func cycle(v int) {
	nodes[v] = true
	for _, vnext := range graph[v] {
		if nodes[vnext] {
			fmt.Println("Draw")
			os.Exit(0)
		}
		cycle(vnext)
	}
	delete(nodes, v)
}

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d %d\n", &n, &m)
	graph = make([][]int, n)
	for i := 0; i < n; i++ {
		var c, tmp int
		fmt.Fscanf(inBuf, "%d", &c)
		for j := 0; j < c; j++ {
			fmt.Fscanf(inBuf, "%d", &tmp)
			graph[i] = append(graph[i], tmp - 1)
		}
		fmt.Fscanf(inBuf, "\n")
	}
	fmt.Fscanf(inBuf, "%d", &start)
	start--
	used = make([][2]bool, n)
	path = make([]int, 0)
	dfs(start, 0)
	nodes = make(map[int]bool)
	cycle(start)
	fmt.Println("Lose")
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner *bufio.Scanner
var t [1e6 + 1]bool

func init_scanner() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024 * 20
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int64 {
	scanner.Scan()
	val, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return val
}

func dfs(x int64, b int64, g [][]int64, marque [][]int64) bool {
	// fmt.Println(x)
	if marque[x][b] == -1 {
		return false
	} else if marque[x][b] > 0 {
		return true
	}

	if len(g[x]) == 0 && b == 1 {
		marque[x][b] = x
		return true
	}

	marque[x][b] = -1
	for _, y := range g[x] {
		if dfs(y, 1-b, g, marque) {
			marque[x][b] = y
			return true
		}
	}

	return false
}

func check_cycle(x int64, g [][]int64, marque_cycle []int64) bool {
	if marque_cycle[x] == 1 {
		return false
	} else if marque_cycle[x] == 2 {
		return true
	}

	marque_cycle[x] = 2
	for _, y := range g[x] {
		if check_cycle(y, g, marque_cycle) {
			return true
		}
	}
	marque_cycle[x] = 1
	return false
}

func main() {
	init_scanner()
	n, _ := readInt(), readInt()
	g, marque := make([][]int64, n+1), make([][]int64, n+1)
	for i := 1; int64(i) <= n; i++ {
		l := readInt()
		g[i] = make([]int64, l)
		marque[i] = make([]int64, 2)
		for j := 0; int64(j) < l; j++ {
			g[i][j] = readInt()
		}
	}
	s := readInt()
	if dfs(s, 0, g, marque) {
		fmt.Println("Win")
		b := 0
		for len(g[s]) > 0 {
			fmt.Printf("%d ", s)
			s = marque[s][b]
			b = 1 - b
		}
		fmt.Println(s)
	} else if check_cycle(s, g, make([]int64, n+1)) {
		fmt.Println("Draw")
	} else {
		fmt.Println("Lose")
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var in = bufio.NewReaderSize(os.Stdin, 2<<16)

func readInt() int {
	var n int
	fmt.Fscan(in, &n)
	return n
}

func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	n := readInt()
	_ = readInt()
	edges := make([][]int, n)
	for i := range edges {
		for c := readInt(); c > 0; c-- {
			edges[i] = append(edges[i], readInt()-1)
		}
	}
	s := readInt() - 1
	type state struct {
		petya bool
		v     int
	}
	q := []state{{true, s}}
	parent := map[state]int{q[0]: 0}
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		if len(edges[v.v]) == 0 && !v.petya {
			var ans []int
			for v != (state{true, s}) {
				ans = append(ans, v.v)
				v.v = parent[v]
				v.petya = !v.petya
			}
			ans = append(ans, s)
			fmt.Fprintln(out, "Win")
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Fprint(out, ans[i]+1)
				if i == 0 {
					fmt.Fprintln(out)
				} else {
					fmt.Fprint(out, " ")
				}
			}
			return
		}
		for _, u := range edges[v.v] {
			uu := state{!v.petya, u}
			if _, has := parent[uu]; has {
				continue
			}
			parent[uu] = v.v
			q = append(q, uu)
		}
	}

	inStack := make([]bool, n)
	visited := make([]bool, n)
	var dfs func(int)
	dfs = func(v int) {
		visited[v] = true
		inStack[v] = true
		for _, u := range edges[v] {
			if !visited[u] {
				dfs(v)
			} else if inStack[u] {
				fmt.Println("Draw")
				os.Exit(0)
			}
		}
		inStack[v] = false
	}

	fmt.Println("Lose")
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func main() {
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	n := readInt()
	_ = readInt()
	edges := make([][]int, n)
	for i := range edges {
		for c := readInt(); c > 0; c-- {
			edges[i] = append(edges[i], readInt()-1)
		}
	}
	s := readInt() - 1
	type state struct {
		petya bool
		v     int
	}
	q := []state{{true, s}}
	parent := map[state]int{q[0]: 0}
	draw := false
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		if len(edges[v.v]) == 0 && !v.petya {
			var ans []int
			for v != (state{true, s}) {
				ans = append(ans, v.v)
				v.v = parent[v]
				v.petya = !v.petya
			}
			ans = append(ans, s)
			fmt.Fprintln(out, "Win")
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Fprint(out, ans[i]+1)
				if i == 0 {
					fmt.Fprintln(out)
				} else {
					fmt.Fprint(out, " ")
				}
			}
			return
		}
		for _, u := range edges[v.v] {
			uu := state{!v.petya, u}
			if _, has := parent[uu]; has {
				draw = true
				continue
			}
			parent[uu] = v.v
			q = append(q, uu)
		}
	}
	if draw {
		fmt.Println("Draw")
	} else {
		fmt.Println("Lose")
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var n, m int
var start int
var graph [][]int
var used [][2]bool
var marked []bool
var path []int

func dfs(v, t int) {
	path = append(path, v)
	if len(graph[v]) == 0 && t == 1 {
		fmt.Println("Win")
		for _, v := range path {
			fmt.Printf("%d ", v+1)
		}
		os.Exit(0)
	}
	used[v][t] = true
	for _, vnext := range graph[v] {
		if !used[vnext][1 - t] {
			dfs(vnext, 1 - t)
		}
	}
	path = path[:len(path) - 1]
}

func cycle(v int) {
	marked[v] = true
	for _, vnext := range graph[v] {
		if marked[vnext] {
			fmt.Println("Draw")
			os.Exit(0)
		}
		cycle(vnext)
	}
}

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d %d\n", &n, &m)
	graph = make([][]int, n)
	for i := 0; i < n; i++ {
		var c, tmp int
		fmt.Fscanf(inBuf, "%d", &c)
		for j := 0; j < c; j++ {
			fmt.Fscanf(inBuf, "%d", &tmp)
			graph[i] = append(graph[i], tmp - 1)
		}
		fmt.Fscanf(inBuf, "\n")
	}
	fmt.Fscanf(inBuf, "%d", &start)
	start--
	used = make([][2]bool, n)
	path = make([]int, 0)
	dfs(start, 0)
	marked = make([]bool, n)
	cycle(start)
	fmt.Println("Lose")
}

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

type Node struct {
	Adj []int
	// The id of the previous node if this node is reachable by odd number of edges.
	// 0 means unknown.
	OddPrev  int
	EvenPrev int
}

const Unknown = 0

func main() {
	r := RapidReader()
	var n, m int
	for {
		if _, err := fmt.Fscan(r, &n, &m); err != nil {
			break
		}
		g := make([]Node, n+1)
		for x := 1; x <= n; x++ {
			var cnt int
			fmt.Fscan(r, &cnt)
			for j := 0; j < cnt; j++ {
				var y int
				fmt.Fscan(r, &y)
				g[x].Adj = append(g[x].Adj, y)
			}
		}
		var s int
		fmt.Fscan(r, &s)

		traversal(g, n, s)

		zeroOut := 0
		winEnd := Unknown
		for x := 1; x <= n; x++ {
			if len(g[x].Adj) == 0 {
				zeroOut++
				if g[x].OddPrev != Unknown {
					winEnd = x
					break
				}
			}
		}

		if winEnd != Unknown {
			fmt.Println("Win")
			var ans []int
			var walk func(int, bool)
			walk = func(x int, odd bool) {
				ans = append(ans, x)
				if odd && x != g[x].OddPrev {
					walk(g[x].OddPrev, false)
				} else if !odd && x != g[x].EvenPrev {
					walk(g[x].EvenPrev, true)
				}
			}
			walk(winEnd, true)
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Printf("%d ", ans[i])
			}
			fmt.Println()
			continue
		}

		if hasCircle(g, n, s) {
			fmt.Println("Draw")
		} else {
			fmt.Println("Lose")
		}
	}
}

func hasCircle(g []Node, n, s int) bool {
	rank := make([]int, n+1, n+1)
	yes := false
	var dfs func(int, int)
	dfs = func(x, r int) {
		rank[x] = r
		for _, y := range g[x].Adj {
			if rank[y] != 0 && rank[y] < r {
				yes = true
			}
			if rank[y] == 0 {
				dfs(y, r+1)
			}
		}
	}
	dfs(s, 1)
	return yes
}

func traversal(g []Node, n, s int) {
	g[s].EvenPrev = s
	stack := []int{s}

	for len(stack) > 0 {
		x := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		for _, y := range g[x].Adj {
			if g[x].OddPrev != Unknown && g[y].EvenPrev == Unknown {
				g[y].EvenPrev = x
				stack = append(stack, y)
			}
			if g[x].EvenPrev != Unknown && g[y].OddPrev == Unknown {
				g[y].OddPrev = x
				stack = append(stack, y)
			}
		}
	}
}

func RapidReader() io.Reader {
	b, _ := ioutil.ReadAll(os.Stdin)
	return bytes.NewReader(b)
}

package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

type Node struct {
	Adj []int
	// The id of the previous node if this node is reachable by odd number of edges.
	// 0 means unknown.
	OddPrev  int
	EvenPrev int
}

const Unknown = 0

func main() {
	r := RapidReader()
	var n, m int
	for {
		if _, err := fmt.Fscan(r, &n, &m); err != nil {
			break
		}
		g := make([]Node, n+1)
		for x := 1; x <= n; x++ {
			var cnt int
			fmt.Fscan(r, &cnt)
			for j := 0; j < cnt; j++ {
				var y int
				fmt.Fscan(r, &y)
				g[x].Adj = append(g[x].Adj, y)
			}
		}
		var s int
		fmt.Fscan(r, &s)

		traversal(g, n, s)

		zeroOut := 0
		winEnd := Unknown
		for x := 1; x <= n; x++ {
			if len(g[x].Adj) == 0 {
				zeroOut++
				if g[x].OddPrev != Unknown {
					winEnd = x
					break
				}
			}
		}

		if winEnd != Unknown {
			fmt.Println("Win")
			var ans []int
			var walk func(x int, odd bool)
			walk = func(x int, odd bool) {
				ans = append(ans, x)
				if odd && x != g[x].OddPrev {
					walk(g[x].OddPrev, false)
				} else if !odd && x != g[x].EvenPrev {
					walk(g[x].EvenPrev, true)
				}
			}
			walk(winEnd, true)
			for i := len(ans) - 1; i >= 0; i-- {
				fmt.Printf("%d ", ans[i])
			}
			fmt.Println()
			continue
		}
		if zeroOut > 0 {
			fmt.Println("Lose")
			continue
		}
		fmt.Println("Draw")
	}
}

func traversal(g []Node, n int, s int) {
	g[s].EvenPrev = s
	var stack []int
	stack = append(stack, s)

	for len(stack) > 0 {
		x := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		for _, y := range g[x].Adj {
			if g[x].OddPrev != Unknown && g[y].EvenPrev == Unknown {
				g[y].EvenPrev = x
				stack = append(stack, y)
			}
			if g[x].EvenPrev != Unknown && g[y].OddPrev == Unknown {
				g[y].OddPrev = x
				stack = append(stack, y)
			}
		}
	}
}

func RapidReader() io.Reader {
	b, _ := ioutil.ReadAll(os.Stdin)
	return bytes.NewReader(b)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

var (
	reader = bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
)

func Println(a ...interface{}) { _, _ = fmt.Fprintln(writer, a...) }

func main() {
	defer func() {
		_ = writer.Flush()
	}()

	T := ReadInt()
	for t := 0; t < T; t++ {
		Solve()
	}
}

func Solve() {
	n := ReadInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ReadInt()
	}
	for len(a) > 1 {
		l := 0
		for i := len(a) - 1; i > 0; i-- {
			if a[i] == 0 {
				l = i
				break
			}
			a[i] = a[i] - a[i-1]
		}
		a = a[1:]
		sort.Slice(a[l:], func(i, j int) bool {
			return a[l+i] < a[l+j]
		})
	}
	Println(a[0])
}

func ReadInt() (value int) {
	_, _ = fmt.Fscan(reader, &value)
	return
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

const cf = true

func solve() {
	var n int
	fmt.Fscan(in, &n)
	arr := make([]int, n)
	notZero := false
	for i := range arr {
		fmt.Fscan(in, &arr[i])
		if arr[i] != 0 {
			notZero = true
		}
	}
	if !notZero {
		fmt.Fprintln(out, 0)
		return
	}
	curZero := 0
	for n > 1 {
		for i := curZero; i < n-1; i++ {
			arr[i] = arr[i+1] - arr[i]
		}
		sliced := arr[curZero : n-1]
		sort.Slice(sliced, func(i, j int) bool {
			return sliced[i] < sliced[j]
		})
		n--
		if curZero > 0 && arr[curZero] != 0 {
			curZero--
		}
		for curZero < n-1 && arr[curZero+1] == 0 {
			curZero++
		}
		if curZero == n-1 && arr[curZero] == 0 {
			fmt.Fprintln(out, 0)
			return
		}
	}
	fmt.Fprintln(out, arr[0])
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"sort"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(A)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(A []int) int {
	// a0, a1, a2
	// a1 - a0, a2 - a1  => sum() = an - a0
	n := len(A)

	for i := n - 1; i >= 1; i-- {
		pre := A[i]
		ok := false
		for j := i - 1; j >= 0; j-- {
			ok = A[j] == 0
			A[j] = pre - A[j]
			pre -= A[j]
			if ok {
				sort.Ints(A[j : i+1])
				break
			}
		}
		if !ok {
			sort.Ints(A[:i])
		}
	}

	return A[0]
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()
	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n, cnt int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
		}
		for i := int64(1); i < n; i++ {
			if len(arr) == 0 {
				break
			}
			sort.Ints(arr)
			b := make([]int, 0)
			if cnt > 0 {
				cnt--
				b = append(b, arr[0])
			}
			for j := 1; j < len(arr); j++ {
				if arr[j] == arr[j-1] {
					cnt++
				} else {
					b = append(b, arr[j]-arr[j-1])
				}
			}
			arr = b
		}
		if cnt > 0 {
			fmt.Fprintln(_w, 0)
		} else {
			fmt.Fprintln(_w, arr[0])
		}
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()
	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n, cnt int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
			if arr[i] == 0 {
				cnt++
			}
		}
		for len(arr) > 1 {
			b := make([]int, 0)
			if cnt > 0 {
				b = append(b, arr[0])
				cnt--
			}
			for i := 1; i < len(arr); i++ {
				x := arr[i] - arr[i-1]
				if x > 0 {
					b = append(b, x)
				} else {
					cnt++
				}
			}
			sort.Ints(b)
			arr = b
		}
		if len(arr) > 0 {
			fmt.Fprintln(_w, arr[0])
		} else {
			fmt.Fprintln(_w, 0)
		}
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()
	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n, cnt int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
			if arr[i] == 0 {
				cnt++
			}
		}
		for len(arr) > 1 {
			b := make([]int, 0)
			if cnt > 0 {
				b = append(b, 0)
				cnt--
			}
			for i := 1; i < len(arr); i++ {
				x := arr[i] - arr[i-1]
				if x > 0 {
					b = append(b, x)
				} else {
					cnt++
				}
			}
			sort.Ints(b)
			arr = b
		}
		if len(arr) > 0 {
			fmt.Fprintln(_w, arr[0])
		} else {
			fmt.Fprintln(_w, 0)
		}
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()

	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
		}
		b := arr
		if b[0] == 0 && b[len(b)-1] == 0 {
			break
		}
		for len(b) > 1 {
			newB := make([]int, len(b)-1)
			for i := 1; i < len(b); i++ {
				newB[i-1] = b[i] - b[i-1]
			}
			b = newB
			sort.Ints(b)
			if b[0] == 0 && b[len(b)-1] == 0 {
				break
			}
		}
		fmt.Fprintln(_w, b[0])
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()

	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
		}
		b := arr
		for len(b) > 1 {
			newB := make([]int, len(b)-1)
			for i := 1; i < len(b); i++ {
				newB[i-1] = b[i] - b[i-1]
			}
			b = newB
			sort.Ints(b)
			i := 1
			for i < len(b) && b[i] == 0 {
				i++
			}
			b = append([]int{b[0]}, b[i:]...)
		}
		fmt.Fprintln(_w, b[0])
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
)

func main() {
	CF1708D(os.Stdin, os.Stdout)
}

func CF1708D(in io.Reader, out io.Writer) {
	_r := bufio.NewReader(in)
	_w := bufio.NewWriter(out)
	defer _w.Flush()

	var T int64
	fmt.Fscan(_r, &T)
	for ; T > 0; T-- {
		var n int64
		fmt.Fscan(_r, &n)
		arr := make([]int, n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(_r, &arr[i])
		}
		b := arr
		for len(b) > 1 {
			newB := make([]int, len(b)-1)
			for i := 1; i < len(b); i++ {
				newB[i-1] = b[i] - b[i-1]
			}
			b = newB
			sort.Ints(b)
			i := 1
			for i+1 < len(b) && b[i+1] == 0 {
				i++
			}
			b = append([]int{b[0]}, b[i:]...)
		}
		fmt.Fprintln(_w, b[0])
	}

}