package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscanf(in, "%d\n", &t)
	for tt := 0; tt < t; tt++ {
		n, k := 0, int64(0)
		fmt.Fscanf(in, "%d %d\n", &n, &k)
		a := make([]int64, 0)
		tmp := int64(0)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &tmp)
			if tmp != 0 {
				a = append(a, tmp)
			}
		}
		fmt.Fscanf(in, "\n")
		n = len(a)
		ok := true
		arr := make([][]int, n)
		for i := 0; i < n; i++ {
			arr[i] = make([]int, 100)
			tmp = a[i]
			//fmt.Println("debug")
			for tmp > 0 {
				//fmt.Println(tmp)
				if tmp != 1 && tmp < k {
					ok = false
					break
				}
				tk := int64(1)
				id := 0
				for tk*k <= tmp {
					tk *= k
					id++
				}
				tmp -= tk
				arr[i][id]++
			}
			//fmt.Println("debug end")
		}
		for i := 0; i < 100; i++ {
			tmp := 0
			for j := 0; j < n; j++ {
				tmp += arr[j][i]
			}
			if tmp > 1 {
				ok = false
			}
		}
		if ok {
			fmt.Fprintf(out, "YES\n")
		} else {
			fmt.Fprintf(out, "NO\n")
		}
	}
	return
}

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

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

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 0; x > 0; i++ {
				r := x % int64(k)
				a[i] += int(r)
				if a[i] > 1 {
					okay = false
					break;
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 0; x > 0; i++ {
				r := x % int64(k)
				a[i] += int(r)
				if a[i] > 1 {
					okay = false
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 {
				continue
			}
			if x % int64(k) != 0 && (x-1) % int64(k) != 0 {
				flag = false
				break
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
			if !flag {
				break
			}
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

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

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

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

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	B := make([][]int64, n)

	for i := 0; i < 60; i++ {
		for j := int64(0); j < n; j++ {
			// memo[A[j]%k]++
			B[j] = append(B[j], A[j]%k)
			A[j] /= k
		}
	}

	for i := int64(0); i < n; i++ {
		B[i] = Reverse(B[i])
	}

	// for i := int64(0); i < n; i++ {
	// 	PrintfDebug("%v\n", B[i])
	// }
	// PrintfDebug("\n")

	for i := 0; i < 60; i++ {
		num := int64(0)
		for j := int64(0); j < n; j++ {
			num += B[j][i]
		}

		if num > 1 {
			fmt.Println("NO")
			return
		}
	}

	fmt.Println("YES")
}

func Reverse(A []int64) []int64 {
	res := []int64{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString 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()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

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

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

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

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

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

package main

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

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

	var ts int
	fmt.Fscanf(r, "%d\n", &ts)

	for t := 0; t < ts; t++ {
		var n int
		var k int64
		fmt.Fscanf(r, "%d %d\n", &n, &k)

		a := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(r, "%d", &a[i])
		}
		fmt.Fscanf(r, "\n")

		fmt.Fprintf(w, "%s\n", can(a, k))
	}
}

func can(a []int64, k int64) string {
	mp := make(map[int]int)
	for _, e := range a {
		p := 0
		for e > 0 {
			r := int(e % k)
			e /= k
			if r > 1 {
				return "NO"
			}
			if r > 0 {
				mp[p]++
				if mp[p] > 1 {
					return "NO"
				}
			}
			p++
		}
	}
	return "YES"
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1312C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t, n, k, v int64
o:
	for Fscan(in, &t); t > 0; t-- {
		cnts := [55]int64{}
		for Fscan(in, &n, &k); n > 0; n-- {
			i := 0
			for Fscan(in, &v); v > 0; v /= k {
				cnts[i] += v % k
				i++
			}
		}
		for _, v := range cnts {
			if v > 1 {
				Fprintln(out, "NO")
				continue o
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
)

func main() {
	for testCase := scanInt(); testCase > 0; testCase--{
		count, kValue := scanInt64(), scanInt64()
		givenArray := scanInt64Slice(int(count))
		hasFound := false
		answerArray := make([]int64, 60)
		for i := int64(0); i < count; i++{
			for j := int64(0); givenArray[i] > 0; j++{
				answerArray[j] += givenArray[i] % kValue
				givenArray[i] /= kValue
			}
		}

		for i := 0; i < 60; i++{
			if answerArray[i] > 1{
				hasFound = true
				break
			}
		}
		if !hasFound{
			printFmt("YES")
		}else{
			printFmt("NO")
		}
	}
	close(channelType)
	oWg.Wait()
}

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

var channelType chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var printFmt func(a ...interface{}) (n int, err error)

func init() {
	printFmt = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}
func min(args ...int) int { mn, _ := minMaxFinder(args...); return mn }
func max(args ...int) int { _, mx := minMaxFinder(args...); return mx }
func minMaxFinder(args ...int) (int, int) { minVal, maxVal := int(math.MaxInt32), int(math.MinInt32); for _, v := range args { if v < minVal { minVal = v }; if v > maxVal { maxVal = v } }; return minVal, maxVal }

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, n int
	var k int64
	fmt.Fscan(reader, &t)
	for z := 0; z < t; z++ {
		fmt.Fscan(reader, &n, &k)
		a := make([]int64, n)
		var ma int64 = 0
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
			if a[i] > ma {
				ma = a[i]
			}
 		}
		var k1 int = 0
		sum := make([]int64, 64)
		vis := make([]bool, 64)
		sum[k1] = 1
		for ; ; k1++ {
			if sum[k1] > ma {
				break
			}
			sum[k1 + 1] = sum[k1] * k
		}
		var flag bool = false
		for i := 0; i < n; i++ {
			for j := k1; j >= 0; j-- {
				if !vis[j] && a[i] >= sum[j] {
					a[i] -= sum[j]
					vis[j] = true
				}
			}
			if a[i] != 0 {
				flag = true
			}
		}
		if flag == false {
			fmt.Fprintln(writer, "YES")
		} else {
			fmt.Fprintln(writer, "NO")
		}
	}
}//2020-07-31 15:24:39.472

package main

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

const INFINITY = math.MaxInt32/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	for t := stdin.ReadInt(); t > 0; t-- {
		n := stdin.ReadInt()
		k := stdin.ReadInt64()
		a := stdin.ReadInt64Slice(n)

		d := map[int]int64{}
		for _, v := range a {
			div := 0
			for v > 0 {
				if _, ok := d[div]; ok {
					d[div] += v % k
				} else {
					d[div] = v % k
				}
				v /= k
				div++
			}
		}

		ok := true
		for _, v := range d {
			if v > 1 {
				ok = false
				break
			}
		}

		if ok {
			stdout.Println("YES")
		} else {
			stdout.Println("NO")
		}
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadInt64() int64 {
	n, _ := strconv.ParseInt(s.Read(), 10, 64)
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadInt64Slice(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt64()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 1; x > 0; i++ {
				if x%int64(k) == 1 {
					a[i] += 1
					if a[i] > 1 {
						okay = false
					}
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 || k == 1{
				continue
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current * k <= x {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 || k == 1{
				continue
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		current, flag, isOverFLow := int64(1), true, false
		ans = strings.Split(string(line), " ")
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if (!isOverFLow && x%current == 0) || (isOverFLow && x == 0) {
				if current > (max / int64(k)) {
					isOverFLow = true
				} else {
					current = current * int64(k)
				}
			} else {
				// fmt.Println(x, current, isOverFLow)
				flag = false
				break
			}
		}
		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		current, flag, isOverFLow := int64(1), true, false
		ans = strings.Split(string(line), " ")
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if (!isOverFLow && x%current == 0) || (isOverFLow && x == 0) {
				current = current * int64(k)
				if current > 10000000000000000 {
					isOverFLow = true
				}
			} else {
				// fmt.Println(x, current, isOverFLow)
				flag = false
				break
			}
		}
		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 {
				continue
			}
			if x % int64(k) != 0 && (x-1) % int64(k) != 0 {
				flag = false
				break
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

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

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

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

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	B := make([][]int64, n)

	for i := 0; i < 60; i++ {
		for j := int64(0); j < n; j++ {
			// memo[A[j]%k]++
			B[j] = append(B[j], A[j]%k)
			A[j] /= k
		}
	}

	for i := int64(0); i < n; i++ {
		B[i] = Reverse(B[i])
	}

	// for i := int64(0); i < n; i++ {
	// 	PrintfDebug("%v\n", B[i])
	// }
	// PrintfDebug("\n")

	for i := 0; i < 60; i++ {
		memo := make([]int, k)
		for j := int64(0); j < n; j++ {
			memo[B[j][i]]++
		}

		for j := int64(1); j < k; j++ {
			if memo[j] > 1 {
				fmt.Println("NO")
				return
			}
		}
	}

	fmt.Println("YES")
}

func Reverse(A []int64) []int64 {
	res := []int64{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString 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()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

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

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

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

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

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

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

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

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

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

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	for i := 0; i < 60; i++ {
		memo := make([]int, 150)
		for j := int64(0); j < n; j++ {
			memo[A[j]%k]++
			A[j] /= k
		}

		for j := int64(1); j < k; j++ {
			if memo[j] > 1 {
				fmt.Println("NO")
				return
			}
		}
	}

	fmt.Println("YES")
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString 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()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

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

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

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

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1312C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t, n, k, v int
o:
	for Fscan(in, &t); t > 0; t-- {
		cnts := [55]int{}
		for Fscan(in, &n, &k); n > 0; n-- {
			i := 0
			for Fscan(in, &v); v > 0; v /= k {
				cnts[i] += v % k
				i++
			}
		}
		for _, v := range cnts {
			if v > 1 {
				Fprintln(out, "NO")
				continue o
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
)

func main() {
	for testCase := scanInt(); testCase > 0; testCase--{
		count, kValue := scanInt(), scanInt()
		givenArray := scanIntSlice(count)
		hasFound := false
		answerArray := make([]int, 60)
		for i := 0; i < count; i++{
			for j := 0; givenArray[i] > 0; j++{
				answerArray[j] += givenArray[i] % kValue
				givenArray[i] /= kValue
			}
		}

		for i := 0; i < 60; i++{
			if answerArray[i] > 1{
				hasFound = true
				break
			}
		}
		if !hasFound{
			printFmt("YES")
		}else{
			printFmt("NO")
		}
	}
	close(channelType)
	oWg.Wait()
}

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

var channelType chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var printFmt func(a ...interface{}) (n int, err error)

func init() {
	printFmt = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}
func min(args ...int) int { mn, _ := minMaxFinder(args...); return mn }
func max(args ...int) int { _, mx := minMaxFinder(args...); return mx }
func minMaxFinder(args ...int) (int, int) { minVal, maxVal := int(math.MaxInt32), int(math.MinInt32); for _, v := range args { if v < minVal { minVal = v }; if v > maxVal { maxVal = v } }; return minVal, maxVal }

package main

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

const INFINITY = math.MaxInt32/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	t := stdin.ReadInt()
	for i := 0; i < t; i++ {
		n := stdin.ReadInt()
		k := stdin.ReadInt()
		a := stdin.ReadIntSlice(n)

		d := map[int]int{}
		for _, v := range a {
			div := 0
			for v > 0 {
				if _, ok := d[div]; ok {
					d[div] += v % k
				} else {
					d[div] = v % k
				}
				v /= k
				div++
			}
		}

		ok := true
		for _, v := range d {
			if v > 1 {
				ok = false
				break
			}
		}

		if ok {
			stdout.Println("YES")
		} else {
			stdout.Println("NO")
		}
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}


package main

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

// github.com/EndlessCheng/codeforces-go
func CF1311F(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct{ v, x int }

	var n int
	Fscan(in, &n)
	x := make([]int, n)
	ps := make([]pair, n)
	for i := range x {
		Fscan(in, &x[i])
	}
	for i := range ps {
		Fscan(in, &ps[i].v)
		ps[i].x = x[i]
	}
	sort.Ints(x)
	sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.v < b.v || a.v == b.v && a.x < b.x })

	ans := int64(0)
	rank := map[int]int{}
	for i, v := range x {
		ans += int64(v) * int64(2*i+1-n)
		rank[v] = i
	}
	for i, p := range ps {
		ans -= int64(p.x) * int64(rank[p.x]-i)
	}
	Fprint(out, ans)
}

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

package main

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

var ans int64
var c [200005][2]int64
var n int

type node struct {
	x int
	v int
}

func lowbit(x int) int {
	return x & (-x)
}
func update(i, val int) {
	for i <= n {
		c[i][0] ++
		c[i][1] += int64(val)
		i += lowbit(i)
	}
}
func query(i, k int) int64 {
	var res int64 = 0
	for i > 0 {
		res += c[i][k]
		i -= lowbit(i)
	}
	return res
}
func unique_sort(slice []int) []int {
	res := make([]int, 0)
	mp := make(map[int]bool, len(slice))
	for _, e := range slice {
		if mp[e] == false {
			mp[e] = true
			res = append(res, e)
		}
	}
	sort.Slice(res, func(i, j int) bool {
		return res[i] < res[j]
	})
	return res
}
func lower_bound(st int, ed int, key int, num []int) int {
	left, right := 1, ed-1
	for ; left < right; {
		mid := (right + left) / 2
		if num[mid] >= key {
			right = mid
		} else {
			left = mid + 1
		}
	}
	if right == ed {
		return ed
	} else {
		return right
	}
}
func main() {
	n = ReadInt()
	a := make([]node, n+1)
	var b []int
	a[0].x = -1e9
	a[0].v = -1e9
	for i := 1; i <= n; i++ {
		a[i].x = ReadInt()
	}
	b = append(b, -1e9)
	for i := 1; i <= n; i++ {
		a[i].v = ReadInt()
		b = append(b, a[i].v)
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i].x < a[j].x;
	})
	b = unique_sort(b)
	for i := 1; i <= n; i++ {
		tmp := lower_bound(1, len(b), a[i].v, b)
		ans += int64(a[i].x) * query(tmp, 0) - query(tmp, 1)
		update(tmp, a[i].x)
	}
	fmt.Println(ans)
}

////////////////////////////////////

func max(a, b int64) int64 {
	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() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, 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 (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1327D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	const mx int = 2e5
	factors := [mx + 1][]int{}
	for i := 1; i <= mx; i++ {
		for j := i; j <= mx; j += i {
			factors[j] = append(factors[j], i)
		}
	}

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &p[i])
			p[i]--
		}
		colors := make([]int, n)
		for i := range colors {
			Fscan(in, &colors[i])
		}

		ans := n
		vis := make([]bool, n)
		for _, v := range p {
			if vis[v] {
				continue
			}
			cs := []int{}
			for ; !vis[v]; v = p[v] {
				vis[v] = true
				cs = append(cs, colors[v])
			}
		o:
			for _, f := range factors[len(cs)] {
				for i, c := range cs[:f] {
					same := true
					for j := i; j < len(cs); j += f {
						if cs[j] != c {
							same = false
							break
						}
					}
					if same {
						if f < ans {
							ans = f
						}
						break o
					}
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

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

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	if n != 1 {
		factors = append(factors, Factor{n, 1})
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	//reader := Reader()
	var t, n int
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	Fscan(in, &t)
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		Fscan(in, &n)
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			Fscan(in, &adj[i])
		}
		for i := 1; i <= n; i++ {
			Fscan(in, &colors[i])
		}

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		Fprintln(out, ans)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1327D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	const mx int = 2e5
	factors := [mx + 1][]int{}
	for i := 1; i <= mx; i++ {
		for j := i; j <= mx; j += i {
			factors[j] = append(factors[j], i)
		}
	}

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &p[i])
			p[i]--
		}
		colors := make([]int, n)
		for i := range colors {
			Fscan(in, &colors[i])
		}

		ans := n
		vis := make([]bool, n)
		for _, v := range p {
			if vis[v] {
				continue
			}
			cs := []int{}
			for ; !vis[v]; v = p[v] {
				vis[v] = true
				cs = append(cs, colors[v])
			}
			for _, f := range factors[len(cs)] {
				same := true
				for i := f; i < len(cs); i += f {
					if cs[i] != cs[0] {
						same = false
						break
					}
				}
				if same && f < ans {
					ans = f
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

package main
import (
	"fmt"
)
import (
	"bufio"
	"os"
	"io"
)

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	if n != 1 {
		factors = append(factors, Factor{n, 1})
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	//reader := Reader()
	var t, n int
	fmt.Scan(&t)
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		fmt.Scan(&n)
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			fmt.Scan(&adj[i])
		}
		for i := 1; i <= n; i++ {
			fmt.Scan(&colors[i])
		}
		fmt.Println(n)
		fmt.Println(adj)
		fmt.Println(colors)

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				fmt.Println(cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		fmt.Println(ans)
	}
}

package main
import (
	"fmt"
)
import (
	"bufio"
	"os"
	"io"
)

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	reader := Reader()
	t := reader()
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		n := reader()
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			adj[i] = reader()
		}
		for i := 1; i <= n; i++ {
			colors[i] = reader()
		}

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		fmt.Println(ans)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"math"
	"runtime/debug"
)

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

type dpcall struct {
	c   byte
	l   int
	r   int
	cnt int
}

var dp map[dpcall]*int64

type anscall struct {
	l int
	r int
}

var ans map[anscall]*int64

var s []byte
var costs []int

func main() {
	//STDOUT MUST BE FLUSHED MANUALLY
	debug.SetGCPercent(-1)
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	s = make([]byte, n)
	var tmp string
	scanf("%s\n", &tmp)
	for i, c := range tmp {
		s[i] = byte(c) - byte('0')
	}

	costs = make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &costs[i])
	}
	// printf("scanned: %v\n", costs)

	// SOLUTION
	// init memoization
	ans = make(map[anscall]*int64)
	dp = make(map[dpcall]*int64)
	printf("%v\n", calcAns(0, n))
}

func calcAns(l, r int) int64 {
	if l >= r {
		return 0
	}
	cal, ok := ans[anscall{l, r}]
	if ok {
		return *cal
	}
	res := int64(0)
	ans[anscall{l, r}] = &res

	for cnt := 1; cnt <= r - l; cnt++ {
		res = max(res, calcDp(0, l, r, cnt) + int64(costs[cnt - 1]))
		res = max(res, calcDp(1, l, r, cnt) + int64(costs[cnt - 1]))
		// printf("res for l(%d), r(%d): %d\n", l, r, res)
	}
	// printf("calcAns(%+v) : %d (cached: %d)\n", anscall{l, r}, res, *ans[anscall{l, r}])
	return res
}

func calcDp(c byte, l, r, cnt int) int64 {
	if cnt == 0 {
		return calcAns(l, r)
	}
	val, ok := dp[dpcall{c, l, r, cnt}]
	if ok {
		return *val
	}
	res := -int64(math.MaxInt64)
	dp[dpcall{c, l, r, cnt}] = &res

	for i := l; i < r; i++ {
		if (c == s[i]) {
			res = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1))
		}
	}
	// printf("calcDp(%+v) : %d (cached: %d)\n", dpcall{c, l, r, cnt}, res, *dp[dpcall{c, l, r, cnt}])
	return res
}

func max(i, f int64) int64 {
	if i > f {
		return i
	}
	return f
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

type dpcall struct {
	c   byte
	l   int
	r   int
	cnt int
}

var dp map[dpcall]*int64

type anscall struct {
	l int
	r int
}

var ans map[anscall]*int64

var s []byte
var costs []int

func main() {
	//STDOUT MUST BE FLUSHED MANUALLY
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	s = make([]byte, n)
	var tmp string
	scanf("%s\n", &tmp)
	for i, c := range tmp {
		s[i] = byte(c) - byte('0')
	}

	costs = make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &costs[i])
	}
	// printf("scanned: %v\n", costs)

	// SOLUTION
	// init memoization
	ans = make(map[anscall]*int64)
	dp = make(map[dpcall]*int64)
	printf("%v\n", calcAns(0, n))
}

func calcAns(l, r int) int64 {
	if l >= r {
		return 0
	}
	cal, ok := ans[anscall{l, r}]
	if ok {
		return *cal
	}
	res := int64(0)
	ans[anscall{l, r}] = &res

	for cnt := 1; cnt <= r - l; cnt++ {
		res = max(res, calcDp(0, l, r, cnt) + int64(costs[cnt - 1]))
		res = max(res, calcDp(1, l, r, cnt) + int64(costs[cnt - 1]))
		// printf("res for l(%d), r(%d): %d\n", l, r, res)
	}
	// printf("calcAns(%+v) : %d (cached: %d)\n", anscall{l, r}, res, *ans[anscall{l, r}])
	return res
}

func calcDp(c byte, l, r, cnt int) int64 {
	if cnt == 0 {
		return calcAns(l, r)
	}
	val, ok := dp[dpcall{c, l, r, cnt}]
	if ok {
		return *val
	}
	res := -int64(math.MaxInt64)
	dp[dpcall{c, l, r, cnt}] = &res

	for i := l; i < r; i++ {
		if (c == s[i]) {
			res = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1))
		}
	}
	// printf("calcDp(%+v) : %d (cached: %d)\n", dpcall{c, l, r, cnt}, res, *dp[dpcall{c, l, r, cnt}])
	return res
}

func max(i, f int64) int64 {
	if i > f {
		return i
	}
	return f
}


package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func print(a ...interface{}) { fmt.Println(a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f + "\n", a...) }

func main() {
	defer writer.Flush()

	var testcases int
	scanf("%d", &testcases)
	for i := 0; i < testcases; i++ {
		scanf("%s")
		var vertices, edges int
		scanf("%d %d", &vertices, &edges)
		graph := make([][][]int, vertices + 1)
		for i := range(graph) {
			graph[i] = make([][]int, 0)
		}
		for j := 0; j < edges; j++ {
			var u, v, w int
			scanf("%d %d %d", &u, &v, &w)
			graph[u] = append(graph[u], []int{v, w})
			graph[v] = append(graph[v], []int{u, w})
		}
		print(solve(graph, vertices))
	}
}

func solve(graph [][][]int, vertices int) int {
	result := (1<<30) - 1
	notInAns := 0
	for i := 30; i >= 0; i-- {
		stack := []int{1}
		seen := make([]int, vertices + 1)
		seenVertices := 0
		notInAns |= (1<<i)
		for len(stack) > 0 {
			current := stack[len(stack) - 1]
			stack = stack[:len(stack) - 1]
			for _, data := range graph[current] {
				next, weight := data[0], data[1]
				if seen[next] == 1 || (weight & notInAns != 0) {
					continue
				}
				stack = append(stack, next)
				seen[next] = 1
				seenVertices += 1
			}
		}
		notInAns &= ^(1<<i)
		if seenVertices == vertices {
			notInAns |= (1<<i)
			result &= ^(1<<i)
		}
	}
	return result
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		readString(reader)
		n, m := readTwoNums(reader)
		E := make([][]int, m)
		for i := 0; i < m; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, m, E)
		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' {
			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(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	vis := make([]int, n)

	var dfs func(u int, mask int)

	dfs = func(u int, mask int) {
		vis[u] = mask
		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if (mask&w) != w || vis[v] == mask {
				continue
			}
			dfs(v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		dfs(0, tmp)

		ok := true

		for i := 0; i < n; i++ {
			if vis[i] != tmp {
				ok = false
				break
			}
		}

		if ok {
			mask = tmp
		}
	}

	return mask
}

func solve1(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	uf := NewUF(n)

	var dfs func(p int, u int, mask int)

	dfs = func(p int, u int, mask int) {

		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if p == v || (mask&w) != w || uf.Find(v) == uf.Find(u) {
				continue
			}
			uf.Union(u, v)
			dfs(u, v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		uf.Reset()
		dfs(-1, 0, tmp)

		if uf.Size() == 1 {
			// good
			mask = tmp
		}
	}

	return mask
}

type UF struct {
	arr  []int
	cnt  []int
	size int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	cnt := make([]int, n)

	for i := 0; i < n; i++ {
		arr[i] = i
		cnt[i]++
	}
	return &UF{arr, cnt, n}
}

func (this *UF) Reset() {
	for i := 0; i < len(this.arr); i++ {
		this.arr[i] = i
		this.cnt[i] = 1
	}
	this.size = len(this.arr)
}

func (this *UF) Find(x int) int {
	if this.arr[x] != x {
		this.arr[x] = this.Find(this.arr[x])
	}
	return this.arr[x]
}

func (this *UF) Union(a, b int) bool {
	pa := this.Find(a)
	pb := this.Find(b)

	if pa == pb {
		return false
	}
	if this.cnt[pa] < this.cnt[pb] {
		pa, pb = pb, pa
	}
	this.cnt[pa] += this.cnt[pb]
	this.arr[pb] = pa
	this.size--
	return true
}

func (this *UF) Size() int {
	return this.size
}

type Graph struct {
	nodes []int
	next  []int
	to    []int
	val   []int
	cur   int
}

func NewGraph(n int, e int) *Graph {
	nodes := make([]int, n)
	next := make([]int, e+3)
	to := make([]int, e+3)
	val := make([]int, e+3)
	var cur int
	return &Graph{nodes, next, to, val, cur}
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.nodes[u]
	g.nodes[u] = g.cur
	g.to[g.cur] = v
	g.val[g.cur] = w
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		readString(reader)
		n, m := readTwoNums(reader)
		E := make([][]int, m)
		for i := 0; i < m; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, m, E)
		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' {
			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(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	uf := NewUF(n)

	var dfs func(p int, u int, mask int)

	dfs = func(p int, u int, mask int) {

		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if p == v || (mask&w) != w || uf.Find(v) == uf.Find(u) {
				continue
			}
			uf.Union(u, v)
			dfs(u, v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		uf.Reset()
		dfs(-1, 0, tmp)

		if uf.Size() == 1 {
			// good
			mask = tmp
		}
	}

	return mask
}

type UF struct {
	arr  []int
	cnt  []int
	size int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	cnt := make([]int, n)

	for i := 0; i < n; i++ {
		arr[i] = i
		cnt[i]++
	}
	return &UF{arr, cnt, n}
}

func (this *UF) Reset() {
	for i := 0; i < len(this.arr); i++ {
		this.arr[i] = i
		this.cnt[i] = 1
	}
	this.size = len(this.arr)
}

func (this *UF) Find(x int) int {
	if this.arr[x] != x {
		this.arr[x] = this.Find(this.arr[x])
	}
	return this.arr[x]
}

func (this *UF) Union(a, b int) bool {
	pa := this.Find(a)
	pb := this.Find(b)

	if pa == pb {
		return false
	}
	if this.cnt[pa] < this.cnt[pb] {
		pa, pb = pb, pa
	}
	this.cnt[pa] += this.cnt[pb]
	this.arr[pb] = pa
	this.size--
	return true
}

func (this *UF) Size() int {
	return this.size
}

type Graph struct {
	nodes []int
	next  []int
	to    []int
	val   []int
	cur   int
}

func NewGraph(n int, e int) *Graph {
	nodes := make([]int, n)
	next := make([]int, e+3)
	to := make([]int, e+3)
	val := make([]int, e+3)
	var cur int
	return &Graph{nodes, next, to, val, cur}
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.nodes[u]
	g.nodes[u] = g.cur
	g.to[g.cur] = v
	g.val[g.cur] = w
}

package main

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

type bufReader struct {
	r   *bufio.Reader
	buf []byte
	i   int
}

var reader = &bufReader{
	bufio.NewReader(os.Stdin),
	make([]byte, 0),
	0,
}

func (r *bufReader) readLine() {
	if r.i < len(r.buf) {
		return
	}
	r.buf = make([]byte, 0)
	r.i = 0
	for {
		line, isPrefix, err := r.r.ReadLine()
		if err != nil {
			panic(err)
		}
		r.buf = append(r.buf, line...)
		if !isPrefix {
			break
		}
	}
}

func (r *bufReader) next() string {
	r.readLine()
	from := r.i
	for ; r.i < len(r.buf); r.i++ {
		if r.buf[r.i] == ' ' {
			break
		}
	}
	s := string(r.buf[from:r.i])
	r.i++
	return s
}

func (r *bufReader) nextLine() string {
	r.readLine()
	s := string(r.buf[r.i:])
	r.i = len(r.buf)
	return s
}

var writer = bufio.NewWriter(os.Stdout)

func next() string {
	return reader.next()
}

func nextInt64() int64 {
	i, err := strconv.ParseInt(reader.next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func nextInt() int {
	return int(nextInt64())
}

func nextLine() string {
	return reader.nextLine()
}

func out(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

func max(x, y int) int {
	return int(max64(int64(x), int64(y)))
}

func min64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func min(x, y int) int {
	return int(min64(int64(x), int64(y)))
}

func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func abs(x int) int {
	return int(abs64(int64(x)))
}

func joinInt64s(a []int64, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.FormatInt(v, 10)
	}
	return strings.Join(b, sep)
}

func joinInts(a []int, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.Itoa(v)
	}
	return strings.Join(b, sep)
}

func divUp64(x, y int64) int64 {
	return (x + y - 1) / y
}

func divUp(x, y int) int {
	return int(divUp64(int64(x), int64(y)))
}

func gcd64(x, y int64) int64 {
	if x < y {
		x, y = y, x
	}
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func gcd(x, y int) int {
	return int(gcd64(int64(x), int64(y)))
}

func lcm64(x, y int64) int64 {
	return x * y / gcd64(x, y)
}

func lcm(x, y int) int {
	return int(lcm64(int64(x), int64(y)))
}

func pow64(x, y int64) int64 {
	return int64(math.Pow(float64(x), float64(y)))
}

func pow(x, y int) int {
	return int(pow64(int64(x), int64(y)))
}

type UnionFind struct {
	root []int
	size []int
}

// New returns an initialized list of size
func New(size int) *UnionFind {
	return new(UnionFind).init(size)
}

// Constructor initializes root and size arrays
func (uf *UnionFind) init(size int) *UnionFind {
	uf = new(UnionFind)
	uf.root = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.root[i] = i
		uf.size[i] = 1
	}

	return uf
}

// Union connects p and q by finding their roots and comparing their respective
// size arrays to keep the tree flat
func (uf *UnionFind) Union(p int, q int) {
	qRoot := uf.Root(q)
	pRoot := uf.Root(p)

	if uf.size[qRoot] < uf.size[pRoot] {
		uf.root[qRoot] = uf.root[pRoot]
		uf.size[pRoot] += uf.size[qRoot]
	} else {
		uf.root[pRoot] = uf.root[qRoot]
		uf.size[qRoot] += uf.size[pRoot]
	}
}

// Root or Find traverses each parent element while compressing the
// levels to find the root element of p
// If we attempt to access an element outside the array it returns -1
func (uf *UnionFind) Root(p int) int {
	if p > len(uf.root)-1 {
		return -1
	}

	for uf.root[p] != p {
		uf.root[p] = uf.root[uf.root[p]]
		p = uf.root[p]
	}

	return p
}

// Root or Find
func (uf *UnionFind) Find(p int) int {
	return uf.Root(p)
}

// Check if items p,q are connected
func (uf *UnionFind) Connected(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

func main() {
	solveTC()
	writer.Flush()
}

func solveTC() {
	t := nextInt()
	for tc := 0; tc < t; tc++ {
		solve()
	}
}

func hasSolution(edges [][]int, allowed []bool, n int) bool {
	unionFind := New(n)
	for i := 0; i < len(allowed); i++ {
		if allowed[i] {
			unionFind.Union(edges[i][0], edges[i][1])
		}
	}
	c := unionFind.Find(0)
	for i := 1; i < n; i++ {
		if unionFind.Find(i) != c {
			return false
		}
	}
	return true
}

func hasSolutionWith(currentOr int64, currentIndex int, edges [][]int, n int, m int) bool {
	allowed := []bool{}
	for i := 0; i < m; i++ {
		currentWeight := int64(edges[i][2])
		toRemove := int64(1)
		if currentIndex > 0 {
			toRemove <<= currentIndex
		}
		toRemove -= 1
		currentWeight = currentWeight & (^toRemove)
		isOk := ((currentOr ^ currentWeight) | currentOr) == currentOr
		if !isOk {
			allowed = append(allowed, false)
		} else {
			allowed = append(allowed, true)
		}
	}
	return hasSolution(edges, allowed, n)
}

func solve() {
	nextLine()
	n := nextInt()
	m := nextInt()
	edges := [][]int{}
	for i := 0; i < m; i++ {
		edges = append(edges, []int{})
		edges[i] = []int{nextInt() - 1, nextInt() - 1, nextInt()}
	}
	currentOr := int64(0)
	for currentIndex := 31; currentIndex >= 0; currentIndex-- {
		if !hasSolutionWith(currentOr, currentIndex, edges, n, m) {
			currentOr |= int64(1) << currentIndex
		}
	}
	out(currentOr)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1624G(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, m, v, w, wt int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		type nb struct{ to, wt int }
		g := make([][]nb, n)
		for ; m > 0; m-- {
			Fscan(in, &v, &w, &wt)
			v--
			w--
			g[v] = append(g[v], nb{w, wt})
			g[w] = append(g[w], nb{v, wt})
		}
		vis := make([]int8, n)
		ans := 0
		for i, m := int8(29), 0; i >= 0; i-- {
			c := n
			m |= 1 << i
			var f func(v int)
			f = func(v int) {
				vis[v] = i + 1
				c--
				for _, e := range g[v] {
					if e.wt&m == 0 && vis[e.to] != i+1 {
						f(e.to)
					}
				}
			}
			f(0)
			if c > 0 {
				ans |= 1 << i
				m &^= 1 << i
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n, m int
	scan(&n, &m)
	var edges = make([]struct{ v1, v2, w int }, m)
	for i := range edges {
		scan(&edges[i].v1, &edges[i].v2, &edges[i].w)
		edges[i].v1--
		edges[i].v2--
	}
	var (
		dsu           = NewDSU(n)
		edgesIdxs, ok = make([]int, m), false
		ans           = 0
	)
	for i := range edgesIdxs {
		edgesIdxs[i] = i
	}
	for bit := 29; bit >= 0; bit-- {
		dsu.Clear()
		if edgesIdxs, ok = check(edges, edgesIdxs, dsu, bit); !ok {
			ans |= 1 << bit
		}
	}
	printf("%v\n", ans)
}

func check(edges []struct{ v1, v2, w int }, edgesIdxs []int, dsu *DSU, bit int) ([]int, bool) {
	edgesIdxsWithZeroedBit := make([]int, 0)
	for _, i := range edgesIdxs {
		if (edges[i].w>>bit)&1 == 1 {
			continue
		}
		edgesIdxsWithZeroedBit = append(edgesIdxsWithZeroedBit, i)
	}
	for _, i := range edgesIdxsWithZeroedBit {
		dsu.Unite(edges[i].v1, edges[i].v2)
	}
	prev := -1
	for i := 0; i < len(dsu.parent); i++ {
		if root := dsu.Root(i); prev != -1 && root != prev {
			return edgesIdxs, false
		} else {
			prev = root
		}
	}
	return edgesIdxsWithZeroedBit, true
}

type DSU struct {
	parent, size []int
}

func NewDSU(n int) *DSU {
	d := &DSU{
		parent: make([]int, n),
		size:   make([]int, n),
	}
	for i := 0; i < n; i++ {
		d.parent[i] = i
		d.size[i] = 1
	}
	return d
}

func (d *DSU) AddSet() {
	n := len(d.parent)
	d.parent = append(d.parent, n)
	d.size = append(d.size, 1)
}

func (d *DSU) Root(i int) int {
	if d.parent[i] == i {
		return i
	}
	d.parent[i] = d.Root(d.parent[i])
	return d.parent[i]
}

func (d *DSU) Unite(i, j int) {
	ri, rj := d.Root(i), d.Root(j)
	if ri == rj {
		return
	}
	if d.size[ri] < d.size[rj] {
		ri, rj = rj, ri
	}
	d.parent[rj] = ri
	d.size[ri] += d.size[rj]
}

func (d *DSU) Clear() {
	for i := range d.parent {
		d.parent[i] = i
	}
	for i := range d.size {
		d.size[i] = 1
	}
}


package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		C := make([][]int, n)
		for i := 0; i < n; i++ {
			C[i] = readNNums(reader, m)
		}
		k, res := solve(n, m, C)
		buf.WriteString(fmt.Sprintf("%d %d\n", k, 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(n int, m int, C [][]int) (int, int64) {
	sum := make([]int64, n)

	for i := 0; i < n; i++ {
		for j := 1; j <= m; j++ {
			sum[i] += int64(C[i][j-1]) * int64(j)
		}
	}

	tmp := sum[0]
	var cnt int
	k := 0
	for i := 1; i < n; i++ {
		if tmp != sum[i] {
			cnt++
			k = i
		}
	}

	if cnt == n-1 {
		// k = 0
		return 1, sum[0] - sum[1]
	}
	// else cnt = 1
	return k + 1, sum[k] - sum[0]
}

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		mbig := big.NewInt(m)
		sums := make([]*big.Int, n)
		for i := 0; i < n; i++ {
			sums[i] = big.NewInt(0)
		}
		for i := 0; i < n; i++ {
			for j := big.NewInt(1); j.Cmp(mbig) <= 0; j.Add(j, big.NewInt(1)) {
				var curr int64
				fmt.Fscan(scanner, &curr)
				tmp := big.NewInt(0)
				tmp = tmp.Mul(big.NewInt(curr), j)
				sums[i].Add(sums[i], tmp)
			}
		}
		//fmt.Println("!!!", sums)
		diff := big.NewInt(0)
		same := big.NewInt(0)
		if sums[0].Cmp(sums[1]) == 0 {
			same = sums[0]
		}
		if sums[0].Cmp(sums[2]) == 0 {
			same = sums[0]
		}
		if sums[1].Cmp(sums[2]) == 0 {
			same = sums[1]
		}
		for i := 0; i < n; i++ {
			if sums[i].Cmp(same) != 0 {
				diff = sums[i]
			}
		}
		// if n%2 == 0 {
		// 	for i := 0; i < n-1; i++ {
		// 		diff.Xor(diff, sums[i])
		// 	}
		// 	if diff.Cmp(big.NewInt(0)) == 0 {
		// 		diff = sums[n-1]
		// 	}
		// } else {
		// 	for i := 0; i < n; i++ {
		// 		diff.Xor(diff, sums[i])
		// 	}
		// }
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i].Cmp(diff) == 0 {
				inum = i + 1
			}
		}
		wres := big.NewInt(0)
		wres = wres.Sub(diff, same)
		fmt.Fprintln(writer, inum, wres)
	}
}

package main

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

var _, _, _ = main, rw, do

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, m)
			for j := range a[i] {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1, w2 := do(n, m, a)
		fmt.Fprintln(w, w1, w2)
	}
}

func do(n, m int, a [][]int) (k int, c int64) {
	var t int64 = -1
	for i, v := range a {
		var s int64
		for j, w := range v {
			s += int64(m - j) * int64(w)
		}
		if t < 0 {
			t = s
			k = i + 1
		} else if t < s {
			c = s - t
		} else if t > s {
			k = i + 1
			c = t - s
		}
	}
	return
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1704D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, m int
	var v int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		for i, pre := 1, int64(0); i <= n; i++ {
			s := int64(0)
			for j := 0; j < m; j++ {
				Fscan(in, &v)
				s += int64(j) * v
			}
			if pre == -1 {
				continue
			}
			if pre == 0 {
				pre = s
			} else if pre != s {
				if s > pre {
					Fprintln(out, i, s-pre)
				} else {
					Fprintln(out, i-1, pre-s)
				}
				pre = -1
			}
		}
	}
}

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

package main

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

var in = bufio.NewReader(os.Stdin)

func read(out *int64) error {
	var ans, sign int64 = 0, 1
	var readed = false
	c, err := in.ReadByte()
	for ; err == nil && (c < '0' || '9' < c); c, err = in.ReadByte() {
		if c == '-' {
			sign = -sign
		}
	}
	for ; err == nil && '0' <= c && c <= '9'; c, err = in.ReadByte() {
		ans = ans<<3 + ans<<1 + int64(c-'0')
		readed = true
	}
	if readed {
		*out = ans * sign
		return nil
	}
	return err
}

var one int64 = 1
var zero int64 = 0
var two int64 = 2
var n, m, p, q, nq int64

func solve() {
	read(&n)
	read(&m)
	var a [][]int64
	for i := zero; i <= n; i++ {
		inline := make([]int64, m+1)
		a = append(a, inline)
	}
	num := make([]int64, n+1)
	for i := one; i <= n; i++ {
		num[i] = 0
	}
	for i := one; i <= n; i++ {
		for j := one; j <= m; j++ {
			read(&(a[i][j]))
			num[i] += a[i][j] * j
		}
	}
	p, q, nq = num[1], -1, 0
	for i := two; i <= n; i++ {
		if num[i] != p {
			q = num[i]
			nq = i
		}
	}
	if p > q {
		fmt.Println(1, p-q)
	} else {
		fmt.Println(nq, q-p)
	}
}
func main() {
	var t int64
	read(&t)
	for i := zero; i < t; i++ {
		solve()
	}
}

package main

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

func main() {
	var n, m int
	f := bufio.NewReader(os.Stdin)
	s, _ := f.ReadString('\n')
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	t, _ := strconv.ParseInt(s, 10, 32)
	for i := 0; i < int(t); i++ {
		s, _ = f.ReadString('\n')
		s = strings.ReplaceAll(s, "\n", "")
		s = strings.ReplaceAll(s, "\r", "")
		_, _ = fmt.Sscanf(s, "%d %d", &n, &m)
		ws := make([]uint64, n)
		for j := 0; j < n; j++ {
			s, _ = f.ReadString('\n')
			s = strings.ReplaceAll(s, "\r", "")
			s = strings.ReplaceAll(s, "\n", "")
			as := strings.SplitN(s, " ", m)
			if len(as) != m {
				panic("kek")
			}
			sum := uint64(0)
			for k, a := range as {
				x, _ := strconv.ParseInt(a, 10, 64)
				sum += uint64(x) * uint64(k)
			}
			ws[j] = sum
		}
		if ws[1] > ws[0] {
			fmt.Println(2, ws[1]-ws[0])
		} else if ws[1] < ws[0] {
			fmt.Println(1, ws[0]-ws[1])
		} else {
			for j := 2; j < n; j++ {
				if ws[j] != ws[0] {
					fmt.Println(j+1, ws[j]-ws[0])
					break
				}
			}
		}
	}
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func slove() {
	var n, m int
	fmt.Fscan(rr, &n, &m)
	nums := make([][]int64, n)
	for i := range nums {
		nums[i] = make([]int64, m)
		for j := range nums[i] {
			fmt.Fscan(rr, &nums[i][j])
		}
	}
	var ans, bei int64
	flag := false
	for i:=1;i<n;i++ {
		for j:=0;j<m-1;j++ {
			ans -= nums[0][j] - nums[i][j]
			nums[i][j+1] -= nums[0][j] - nums[i][j]
			nums[i][j] = nums[0][j]
		}
		if ans != 0 {
			if i == 1 {
				flag = true
				bei = ans
				ans = 0
			} else if flag {
				fmt.Fprintln(ww, 1, abs(bei))
				return
			} else {
				fmt.Fprintln(ww, i+1, abs(ans))
				return
			}
		} else if flag {
			fmt.Fprintln(ww, 2, abs(bei))
			return
		}
	}
}

func abs(a int64) int64 {if a < 0 {return -a} else {return a}}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		mbig := big.NewInt(m)
		sums := make([]*big.Int, n)
		for i := 0; i < n; i++ {
			sums[i] = big.NewInt(0)
		}
		for i := 0; i < n; i++ {
			for j := big.NewInt(1); j.Cmp(mbig) <= 0; j.Add(j, big.NewInt(1)) {
				var curr int64
				fmt.Fscan(scanner, &curr)
				tmp := big.NewInt(0)
				tmp = tmp.Mul(big.NewInt(curr), j)
				sums[i].Add(sums[i], tmp)
			}
		}
		//fmt.Println("!!!", sums)
		diff := big.NewInt(0)
		if n%2 == 0 {
			for i := 0; i < n-1; i++ {
				diff.Xor(diff, sums[i])
			}
			if diff.Cmp(big.NewInt(0)) == 0 {
				diff = sums[n-1]
			}
		} else {
			for i := 0; i < n; i++ {
				diff.Xor(diff, sums[i])
			}
		}
		same := sums[0]
		if same.Cmp(diff) == 0 {
			same = sums[1]
		}
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i].Cmp(diff) == 0 {
				inum = i + 1
			}
		}
		wres := big.NewInt(0)
		wres = wres.Sub(diff, same)
		fmt.Fprintln(writer, inum, wres)
	}
}

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		sums := make([]int64, n)
		for i := 0; i < n; i++ {
			for j := int64(1); j <= m; j++ {
				var curr int64
				fmt.Fscan(scanner, &curr)
				sums[i] += curr * j
			}
		}
		diff := int64(0)
		if n%2 == 0 {
			for i := 0; i < n-1; i++ {
				diff ^= sums[i]
			}
			if diff == 0 {
				diff = sums[n-1]
			}
		} else {
			for i := 0; i < n; i++ {
				diff ^= sums[i]
			}
		}
		var same int64
		same = sums[0]
		if same == diff {
			same = sums[1]
		}
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i] == diff {
				inum = i + 1
			}
		}
		fmt.Fprintln(writer, inum, diff-same)
	}
}

package main

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

var _, _, _ = main, rw, do

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, m)
			for j := range a[i] {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1, w2 := do(n, m, a)
		fmt.Fprintln(w, w1, w2)
	}
}

func do(n, m int, a [][]int) (k int, c int) {
	t := -1
	for i, v := range a {
		s := 0
		for j, w := range v {
			s += (m - j) * w
		}
		if t < 0 {
			t = s
			k = i + 1
		} else if t < s {
			c = s - t
		} else if t > s {
			k = i + 1
			c = t - s
		}
	}
	return
}


package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		if in%2==0{
			fmt.Println(in*4+1)
		}else if in%4==1{
			fmt.Println(in*2+1)
		}else{
			fmt.Println(in+1)
		}
	}
}

package main

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

func scanInt(scanner *bufio.Scanner) int {
  scanner.Scan()
  x, _ := strconv.Atoi(scanner.Text())
  return x
}

func gcd(a, b int64) int64 {
  for b != 0 {
    a, b = b, a%b
  }
  return a
}

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  t := scanInt(scanner)
  for i := 0; i < t; i++ {
    n := int64(scanInt(scanner))
    result := 4*n / gcd(n+1, 4*n) + 1
    writer.WriteString(fmt.Sprintf("%d\n", result))
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    switch (n+1)%4 {
      case 0: fmt.Println(n+1)
      case 2: fmt.Println(2*n+1)
      default: fmt.Println(4*n+1)
    }
  }
}

// 194B
package main

import (
	"fmt"
)

func gcd(u, v int64) int64 {
	for v != 0 {
		r := u % v
		u = v
		v = r
	}
	return u
}

func main() {
	var t, i int64
	fmt.Scan(&t)
	for ; t > 0; t-- {
		fmt.Scan(&i)
		fmt.Println(1 + (4*i)/gcd(4*i, i+1))
	}
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n int
  fmt.Scanf("%d", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n int
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    switch n%4 {
      case 0: fmt.Println(n+1)
      case 2: fmt.Println(2*n+1)
      default: fmt.Println(4*n+1)
    }
  }
}

package main
import "fmt"

func main(){
	var n,in int
	fmt.Scan(&n)
	for i:=0; i<n; i++ {
		fmt.Scan(&in)
		fmt.Println(in*4+1)
	}
}

package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		if in%2 == 0{
			fmt.Println(in*4+1)
		}else{
			fmt.Println(in*2+1)
		}
	}
}

package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		fmt.Println(in*4+1)
	}
}