package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"sort"
)

var scanner *bufio.Scanner

func init() {
	scanner = bufio.NewScanner(bufio.NewReaderSize(os.Stdin, 1<<20))
	scanner.Split(bufio.ScanWords)
}

func NextInt64() int64 {
	scanner.Scan()
	var res int64
	var negative bool
	bytes := scanner.Bytes()
	if bytes[0] == '-' {
		negative = true
		bytes = bytes[1:]
	}
	for _, c := range bytes {
		res = res*10 + int64(c - '0')
	}
	if negative {
		res = -res
	}
	return res
}

func NextInt() int {
	return int(NextInt64())
}

var xx []uint64

func calculateForBit(prefix uint64, bit uint, old []uint64, new []uint64) (int64, []uint64) {
	res := int64(0)
	l, r := 0, 0

	for i := 0; i < len(old); {
		var j1, j2 int

		left := (((old[i] ^ prefix) >> bit) ^ 1) << bit
		right := left + (1 << bit)

		for ; l < len(xx) && xx[l] < left; l++ {
		}
		for ; r < len(xx) && xx[r] < right; r++ {
		}

		for j1 = i; j1 < len(old) && old[j1]>>bit == old[i]>>bit; j1++ {
			res += int64(r - l)
		}

		if j1 != len(old) {
			left = (((old[j1] ^ prefix) >> bit) ^ 1) << bit
			right = left + (1 << bit)

			for ; l < len(xx) && xx[l] < left; l++ {
			}
			for ; r < len(xx) && xx[r] < right; r++ {
			}
		}

		for j2 = j1; j2 < len(old) && old[j2]>>(bit+1) == old[i]>>(bit+1); j2++ {
			res += int64(r - l)
		}

		copy(new[i:i+j2-j1], old[j1:j2])
		copy(new[i+j2-j1:j2], old[i:j1])
		i = j2
	}

	return res, new
}

func main() {

	n := NextInt()
	k := NextInt64() - 1

	xx = make([]uint64, n)

	for i := 1; i < n; i++ {
		p := NextInt()
		v := uint64(NextInt64())
		p--
		xx[i] = xx[p] ^ v
	}

	rand.Shuffle(n, func(i, j int) {
		xx[i], xx[j] = xx[j], xx[i]
	})

	sort.Slice(xx, func(i, j int) bool {
		return xx[i] < xx[j]
	})

	current := make([]uint64, n)
	copy(current, xx)

	buf := make([]uint64, n)

	sum := int64(0)
	answer := uint64(0)

	for i := 61; i >= 0; i-- {
		if res, newArr := calculateForBit(answer^(1<<uint(i)), uint(i), current, buf); sum+res <= k {
			sum += res
			current, buf = newArr, current
			answer ^= 1 << uint(i)
		}
	}

	fmt.Println(answer)
}

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"sort"
)

var scanner *bufio.Scanner

func init() {
	scanner = bufio.NewScanner(bufio.NewReaderSize(os.Stdin, 1<<20))
	scanner.Split(bufio.ScanWords)
}

func NextInt64() int64 {
	scanner.Scan()
	var res int64
	var negative bool
	bytes := scanner.Bytes()
	if bytes[0] == '-' {
		negative = true
		bytes = bytes[1:]
	}
	for _, c := range bytes {
		res = res*10 + int64(c - '0')
	}
	if negative {
		res = -res
	}
	return res
}

func NextInt() int {
	return int(NextInt64())
}

var xx []uint64

func calculateForBit(prefix uint64, bit uint, old []uint64, new []uint64) (int64, []uint64) {
	res := int64(0)
	l, r := 0, 0

	for i := 0; i < len(old); {
		var j1, j2 int

		left := (((old[i] ^ prefix) >> bit) ^ 1) << bit
		right := left + (1 << bit)

		for ; l < len(xx) && xx[l] < left; l++ {
		}
		for ; r < len(xx) && xx[r] < right; r++ {
		}

		for j1 = i; j1 < len(old) && old[j1]>>bit == old[i]>>bit; j1++ {
			res += int64(r - l)
		}

		if j1 != len(old) {
			left = (((old[j1] ^ prefix) >> bit) ^ 1) << bit
			right = left + (1 << bit)

			for ; l < len(xx) && xx[l] < left; l++ {
			}
			for ; r < len(xx) && xx[r] < right; r++ {
			}
		}

		for j2 = j1; j2 < len(old) && old[j2]>>(bit+1) == old[i]>>(bit+1); j2++ {
			res += int64(r - l)
		}

		copy(new[i:i+j2-j1], old[j1:j2])
		copy(new[i+j2-j1:j2], old[i:j1])
		i = j2
	}

	return res, new
}

func main() {

	n := NextInt()
	k := NextInt64() - 1

	xx = make([]uint64, n)

	for i := 1; i < n; i++ {
		p := NextInt()
		v := uint64(NextInt64())
		p--
		xx[i] = xx[p] ^ v
	}

	rand.Shuffle(n, func(i, j int) {
		xx[i], xx[j] = xx[j], xx[i]
	})

	sort.Slice(xx, func(i, j int) bool {
		return xx[i] < xx[j]
	})

	current := make([]uint64, n)
	copy(current, xx)

	buf := make([]uint64, n)

	sum := int64(0)
	answer := uint64(0)

	for i := 62; i >= 0; i-- {
		if res, newArr := calculateForBit(answer^(1<<uint(i)), uint(i), current, buf); sum+res <= k {
			sum += res
			current, buf = newArr, current
			answer ^= 1 << uint(i)
		}
	}

	fmt.Println(answer)
}

package main

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

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

var xx []uint64

type Node struct {
	ch [2]*Node
	sum int32
}

func getSum(node *Node) int64 {
	if node == nil {
		return 0
	}
	return int64(node.sum)
}

func findSum(root *Node, x uint64, k uint64) int64 {
	x = bits.Reverse64(x)
	k = bits.Reverse64(k)

	res := int64(0)

	for i := 0; i < 64 && getSum(root) > 0; i++ {
		if k & 1 == 1 {
			res += getSum(root.ch[x & 1])
		}
		root = root.ch[(x ^ k) & 1]
		x >>= 1
		k >>= 1
	}

	return res
}

func build(values []uint64) *Node {
	root := &Node{}
	for _, x := range values {
		x = bits.Reverse64(x)
		node := root
		for i := 0; i < 64; i++ {
			node.sum += 1
			if node.ch[x & 1] == nil {
				node.ch[x & 1] = &Node{}
			}
			node = node.ch[x & 1]
			x >>= 1
		}
		node.sum += 1
	}

	return root
}

func findLess(root *Node, values []uint64, k uint64) int64 {
	res := int64(0)
	for _, v := range values {
		res += findSum(root, v, k)
	}
	return res
}

func main() {

	var (
		n int
		k int64
	)

	fmt.Fscan(in, &n, &k)
	k--

	xx = make([]uint64, n)

	for i := 1; i < n; i++ {
		var p int
		var v uint64
		fmt.Fscan(in, &p, &v)
		p--
		xx[i] = xx[p] ^ v
	}

	root := build(xx)
	l, r := uint64(0), uint64(1 << 62)

	//for i := 0; i < 7; i++ {
	//	fmt.Println(i, findLess(root, xx, uint64(i)))
	//}

	for ; l < r; {
		m := (l + r) / 2
		if findLess(root, xx, m) >= k {
			r = m
		} else {
			l = m + 1
		}
	}
	fmt.Println(l)
}

package main

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

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

var xx []uint64

type Node struct {
	ch [2]*Node
	sum int32
}

func getSum(node *Node) int64 {
	if node == nil {
		return 0
	}
	return int64(node.sum)
}

func findSum(root *Node, x uint64, k uint64) int64 {
	x = bits.Reverse64(x)
	k = bits.Reverse64(k)

	res := int64(0)

	for i := 0; i < 64 && getSum(root) > 0; i++ {
		if k & 1 == 1 {
			res += getSum(root.ch[x & 1])
		}
		root = root.ch[(x ^ k) & 1]
		x >>= 1
		k >>= 1
	}

	return res
}

func build(values []uint64) *Node {
	root := &Node{}
	for _, x := range values {
		x = bits.Reverse64(x)
		node := root
		for i := 0; i < 64; i++ {
			node.sum += 1
			if node.ch[x & 1] == nil {
				node.ch[x & 1] = &Node{}
			}
			node = node.ch[x & 1]
			x >>= 1
		}
	}

	return root
}

func findLess(root *Node, values []uint64, k uint64) int64 {
	res := int64(0)
	for _, v := range values {
		res += findSum(root, v, k)
	}
	return res
}

func main() {

	var (
		n int
		k int64
	)

	fmt.Fscan(in, &n, &k)
	k--

	xx = make([]uint64, n)

	for i := 1; i < n; i++ {
		var p int
		var v uint64
		fmt.Fscan(in, &p, &v)
		p--
		xx[i] = xx[p] ^ v
	}

	root := build(xx)
	l, r := uint64(0), uint64(1 << 62)

	//for i := 0; i < 7; i++ {
	//	fmt.Println(findLess(root, xx, uint64(i)))
	//}

	for ; l < r; {
		m := (l + r) / 2
		if findLess(root, xx, m) >= k {
			r = m
		} else {
			l = m + 1
		}
	}
	fmt.Println(l)
}

package main

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

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

var xx []uint64

func calculateForBit(prefix uint64, bit uint, old []uint64, new []uint64) (int64, []uint64) {
	res := int64(0)
	l, r := 0, 0

	doUpdate := func(left, right uint64, multiplier int64) {
		//println("! ", left, " ", right, " ", multiplier)
		for ; l < len(xx) && xx[l] < left; l++ {
		}
		for ; r < len(xx) && xx[r] < right; r++ {
		}
		res += int64(r-l) * multiplier
	}

	for i := 0; i < len(old); {
		var j1, j2 int

		for j1 = i; j1 < len(old) && (old[j1]^prefix)>>bit == (old[i]^prefix)>>bit; j1++ {
		}

		left := (((old[i] ^ prefix) >> bit) ^ 1) << bit
		right := left + (1 << bit)
		doUpdate(left, right, int64(j1 - i))

		for j2 = j1; j2 < len(old) && (old[j2]^prefix)>>(bit+1) == (old[i]^prefix)>>(bit+1); j2++ {
		}

		if j2 > j1 {
			left := (((old[j1] ^ prefix) >> bit) ^ 1) << bit
			right := left + (1 << bit)
			doUpdate(left, right, int64(j2 - j1))
		}

		new = append(new, old[j1:j2]...)
		new = append(new, old[i:j1]...)
		i = j2
	}

	//println(prefix, " ", bit, " ", res)
	return res, new
}

func main() {

	var (
		n int
		k int64
	)

	fmt.Fscan(in, &n, &k)
	k--

	xx = make([]uint64, n)

	for i := 1; i < n; i++ {
		var p int
		var v uint64
		fmt.Fscan(in, &p, &v)
		p--
		xx[i] = xx[p] ^ v
	}

	sort.Slice(xx, func(i, j int) bool {
		return xx[i] < xx[j]
	})

	current := make([]uint64, n)
	copy(current, xx)

	new := make([]uint64, n)

	sum := int64(0)
	answer := uint64(0)

	for i := 62; i >= 0; i-- {
		if res, newArr := calculateForBit(answer^ (1 << uint(i)), uint(i), current, new[:0]); sum + res <= k {
			sum += res
			current, new = newArr, current
			answer ^= 1 << uint(i)
		}
	}

	println(answer)
}


package main

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

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

	var t int
	var a, b, n, m int64

	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &a, &b, &n, &m)
		if a > b {
			a, b = b, a
		}
		if a < m {
			fmt.Fprintln(w, "NO")
			continue
		}
		if a+b < m+n {
			fmt.Fprintln(w, "NO")
			continue
		}

		fmt.Fprintln(w, "YES")
	}
}

package main

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

var DEBUG = true

func main() {
	defer Flush()

	T := readi()
	for t := 0; t < T; t++ {
		a := readll()
		b := readll()
		n := readll()
		m := readll()
		if solve(a, b, n, m) {
			println("Yes")
		} else {
			println("No")
		}
	}
}

func solve(a, b, n, m int64) bool {
	k := minll(n, m)

	a -= k
	b -= k
	if a < 0 || b < 0 {
		return false
	}

	m -= k
	n -= k
	if n == 0 && m == 0 {
		//dbg(a+k, b+k, n+k, m+k, "=>", a, b, n, m)
		return true
	}
	if 0 < n {
		//dbg(a+k, b+k, n+k, m+k, "=>", a, b, n, m)
		return n <= a+b
	}
	//dbg(a+k, b+k, n+k, m+k, "=>", a, b, n, m)
	return m <= minll(a, b)
}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

func dbgf(f string, args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintf(os.Stderr, f, args...)
}

func dbg(args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

func minf(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

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

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

func maxf(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

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

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

package main

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

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

	var t int
	var a, b, n, m int64

	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &a, &b, &n, &m)

		if (min(a, b) >= m) && (a+b >= m+n) {
			fmt.Fprintln(w, "YES")
		} else {
			fmt.Fprintln(w, "NO")
		}
	}
}

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

	return b
}

package main

import "fmt"

func main() {
	var tc int
	fmt.Scanf("%d\n", &tc)
	for ; tc > 0; tc-- {
		var a, b, n, m, tmp int64
		fmt.Scanf("%d%d%d%d\n", &a, &b, &n, &m)
		if a < b {
			tmp = a
		} else {
			tmp = b
		}
		if a+b < n+m || m-tmp > 0 {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
	}
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

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

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	var t, a, b, n, m int64
	scanf("%d", &t)

	for ; t > 0; t-- {
		scanf("\n%d %d %d %d", &a, &b, &n, &m)
		if a+b < n+m || min(a, b) < m {
			printf("No\n")
		} else {
			printf("Yes\n")
		}
	}
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		var a, b, n, m uint64
		s, _ := reader.ReadBytes('\n')
		pos := readUint64(s, 0, &a)
		pos = readUint64(s, pos+1, &b)
		pos = readUint64(s, pos+1, &n)
		pos = readUint64(s, pos+1, &m)
		res := solve(int64(a), int64(b), int64(n), int64(m))
		if res {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

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

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

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

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

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

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

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

	return i
}

func solve(a, b, n, m int64) bool {
	return n+m <= a+b && m <= min(a, b)
}

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

package main

import (
	"fmt"
)

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

func main() {
	var tt int
	var a, b, n, m int64

	fmt.Scan(&tt)

	for tt != 0 {
		fmt.Scan(&a, &b, &n, &m)
		if a+b < n+m {
			fmt.Println("No")
		} else if m <= min(a, b) {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
		tt--
	}
}

/*
URL:
https://codeforces.com/contest/1371/problem/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
	// MOD          = 998244353
	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

	a, b, n, m int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		a, b, n, m = ReadInt64_4()

		solve()
	}
}

func solve() {
	if a+b < n+m {
		fmt.Println("No")
		return
	}

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

	if b < m {
		fmt.Println("No")
		return
	}

	b -= m
	if a+b < n {
		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 (
	"fmt"
)

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

func main() {
	var tt int
	var a, b, n, m int64

	fmt.Scan(&tt)

	for tt != 0 {
		fmt.Scan(&a, &b, &n, &m)
		if a+b < n+m {
			println("No")
		} else if m <= min(a, b) {
			println("Yes")
		} else {
			println("No")
		}
		tt--
	}
}


package main

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

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

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

	for ; t > 0; t-- {
		var p, a, b, c int64
		fmt.Fscan(in, &p, &a, &b, &c)
		if (p%a)*(p%b)*(p%c) == 0 {
			fmt.Println(0)
		} else {
			fmt.Println(min(a-p%a, b-p%b, c-p%c))
		}
	}
}

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

package main

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

type CF1492A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1492A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1492A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1492A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1492A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1492A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1492A
Date: 25/11/21
User: epradere
URL: https://codeforces.com/problemset/problem/1492/A
Problem: CF1492A
**/
func (in *CF1492A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		p, a, b, c := in.NextInt64(), in.NextInt64(), in.NextInt64(), in.NextInt64()

		ans := a - (p % a)
		aux := a - (p % a)
		if aux == a {
			ans = 0
		}
		ans = Min(ans, aux)
		aux = b - (p % b)
		if aux == b {
			ans = 0
		}
		ans = Min(ans, aux)
		aux = c - (p % c)
		if aux == c {
			ans = 0
		}
		ans = Min(ans, aux)
		fmt.Println(ans)

	}

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

func NewCF1492A(r *bufio.Reader) *CF1492A {
	return &CF1492A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1492A(bufio.NewReader(os.Stdin)).Run()
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var p, a, b, c int64
	var t int

	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &p, &a, &b, &c)
		ans := findClass(p, a)
		ans = min(ans, findClass(p, b))
		ans = min(ans, findClass(p, c))
		fmt.Println(ans)
	}
}

func findClass(p, a int64) int64 {
	remind := p % a
	if remind == 0 {
		return 0
	}
	return a - remind
}
func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

package main

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

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func solve() {
	p := getI()
	o := int64(math.MaxInt64)
	for i := 0; i < 3; i++ {
		cur := getI()
		res := p % cur
		if res > 0 {
			res = cur - res
		}
		o = min(o, res)
	}
	out(o)
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	for i := getI(); i > 0; i-- {
		solve()
	}
	out()
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(wr, f, a...)
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []int64 {
	ret := make([]int64, N)
	for i := range ret {
		ret[i] = getI()
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func nsort(data ...int64) {
	sort.Slice(data, func(i, j int) bool { return data[i] < data[j] })
}

func nsum(data ...int64) int64 {
	var res int64
	for _, n := range data {
		res += n
	}
	return res
}

func njoin(s ...int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int64, fn func(int64)) {
	for i := int64(0); i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

package main

import "fmt"

func main() {
	var nums,a,b,c,now uint64
	fmt.Scanln(&nums)
	for i := 0; i < int(nums); i++{
		fmt.Scanln(&now,&a,&b,&c)
		minWait := b
		if now % a == 0 || now % b == 0 || now % c == 0{
			fmt.Println(0)
			continue
		}
		a,b,c = a - (now % a),b - (now % b),c - (now % c)
		if a == 0 || a < b{
			minWait = a
		}else{
			minWait = b
		}
		if c == 0 || c < minWait{
			minWait = c
		}
		fmt.Println(minWait)
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	p      int64
)

func min(x, y int) int {
	if x > y {
		return y
	}
	return x
}

func solve(p int64, a []int64) int64 {
	for i := range a {
		r := p % a[i]
		if r == 0 {
			a[i] = 0
		} else {
			a[i] -= r
		}
	}
	x := a[0]
	if a[1] < x {
		x = a[1]
	}
	if a[2] < x {
		x = a[2]
	}
	return x
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		a := make([]int64, 3)
		fmt.Fscan(reader, &p, &a[0], &a[1], &a[2])
		fmt.Println(solve(p, a))
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(time int64, speeds []int64) int64 {
	firstMeet := int64(1 << 62)
	for _, speed := range speeds {
		laps := (time + speed - 1) / speed
		if meet := laps * speed; meet < firstMeet {
			firstMeet = meet
		}
	}
	return firstMeet - time
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i += 1 {
		time := stdin.Int64()
		speeds := stdin.Int64s(3)

		res := solve(time, speeds)
		fmt.Println(res)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int32
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		var p, a, b, c int64
		fmt.Scanf("%d %d %d %d\n", &p, &a, &b, &c)

		f := func(x, p int64) int64 {
			return (x - p % x) % x
		}

		res := f(a, p)
		if res > f(b, p) {
			res = f(b, p)
		}
		if res > f(c, p) {
			res = f(c, p)
		}
		fmt.Println(res)
	}

}

package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"math"
	"os"
	"strings"
)

var bytes []byte

func nextByte() byte {
	b := bytes[0]
	bytes = bytes[1:]
	return b
}

func ScanInt64() int64 {
	var negative bool
	var result int64

	b := nextByte()

	for ; b < '0' || b > '9'; b = nextByte() {
		if b == '-' {
			negative = true
		}
	}

	for ; '0' <= b && b <= '9'; b = nextByte() {
		result = (result << 3) + (result << 1) + int64(b-'0')
	}

	if negative {
		return -result
	} else {
		return result
	}
}

func ScanInt() int {
	return int(ScanInt64())
}

func ScanString() string {
	builder := strings.Builder{}

	for b := nextByte(); b != '\r'; b = nextByte() {
		if b != '\n' {
			builder.WriteByte(b)
		}
	}

	return builder.String()
}

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, _ = ioutil.ReadAll(bufio.NewReader(f))
}

func main() {
	for t := ScanInt(); t > 0; t-- {
		p, a, b, c := ScanInt64(), ScanInt64(), ScanInt64(), ScanInt64()
		fmt.Println(min((a-p%a)%a, (b-p%b)%b, (c-p%c)%c))
	}
}

func min(a ...int64) int64 {
	res := int64(math.MaxInt64)

	for _, e := range a {
		if e < res {
			res = e
		}
	}

	return res
}

package main

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

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

func scanf(pattern string, a ...interface{})  { fmt.Fscanf(reader, pattern, a...) }
func printf(pattern string, a ...interface{}) { fmt.Fprintf(writer, pattern, a...) }
func ceil(a, b int64) int64                   { return (a + b - 1) / b }
func min(a, b int64) int64 {
	if a < b {
		return a
	} else {
		return b
	}
}
func max(a, b int64) int64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func main() {
	defer writer.Flush()
	var T int
	scanf("%d\n", &T)
	for t := 0; t < T; t++ {
		var p, a, b, c int64
		scanf("%d %d %d %d\n", &p, &a, &b, &c)
		var ans int64
		// printf("%d %d %d\n", ceil(p, a), ceil(p, b), ceil(p, c))
		ans = min(ceil(p, a)*a-p, min(ceil(p, b)*b-p, ceil(p, c)*c-p))
		printf("%d\n", ans)
	}
}

package main

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

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

func main() {
	defer writer.Flush()
	var testcases int
	fmt.Fscan(reader, &testcases)

	var p, min int64
	var time [3]int64
	for testcase := 0; testcase < testcases; testcase++ {
		min = math.MaxInt64
		fmt.Fscan(reader, &p, &(time[0]), &(time[1]), &(time[2]))
		for i, v := range time {
			time[i] = v - (p % v)
			if time[i] == v {
				time[i] = 0
				min = 0
				break
			}
			if min > time[i] {
				min = time[i]
			}
		}
		fmt.Fprintln(writer, min)
	}
}

// http://codeforces.com/problemset/problem/1492/A

package main

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

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

	var t int
	fmt.Fscan(input, &t)

	for ; t > 0; t-- {
		var p, a, b, c int64
		//var result int64 = min(a-p%a, b-p%b, c-p%c)

		fmt.Fscan(input, &p, &a, &b, &c)

		if (p%a)*(p%b)*(p%c) == 0 {
			fmt.Println("0")
		} else {
			fmt.Println(min(a-p%a, b-p%b, c-p%c))
		}
	}
}

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

package main

import "fmt"

func mymin(a, b int64) int64 {
	var ret int64
	if a <= b {
		ret = a
	} else {
		ret = b
	}
	return ret
}

func main() {
	var T, a, b, c, p int64
	fmt.Scan(&T)
	for T > 0 {
		T--
		fmt.Scan(&p, &a, &b, &c)
		var answer int64 = 1000000000000000000
		if (p%a == 0) || (p%b == 0) || (p%c == 0) {
			answer = 0
		}
		answer = mymin(answer, a-p%a)
		answer = mymin(answer, b-p%b)
		answer = mymin(answer, c-p%c)
		fmt.Println(answer)
	}
}

package main

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

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

    var t int
    fmt.Fscan(r, &t);
    for i := 0; i < t; i++ {
        var p, a, b, c int64
        fmt.Fscan(r, &p, &a, &b, &c);
        f := func(x int64) int64 {
            if p % x == 0 {
                return 0
            } else {
                return x - p % x
            }
        }
        a = f(a)
        b = f(b)
        c = f(c)
        var n int64
        if a <= b  {
            if a <= c {
                n = a
            } else {
                n = c
            }
        } else {
            if b <= c {
                n = b
            } else {
                n = c
            }
        }
        fmt.Fprintln(w, n)
    }
}

package main

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

func solveA() {
	var p, a, b, c int64
	scan(&p, &a, &b, &c)
	ans := int64(1e18) + 1
	ans = min(ans, (a-p%a)%a)
	ans = min(ans, (b-p%b)%b)
	ans = min(ans, (c-p%c)%c)
	printf("%d\n", ans)
}

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

func solveB() {}

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

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

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

package main

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

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

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var p, a, b, c int64

		fmt.Fscan(input, &p)
		fmt.Fscan(input, &a)
		fmt.Fscan(input, &b)
		fmt.Fscan(input, &c)

		// XARRAY := make([]int, n)
		// STRING := make([]byte, 0)
		// fmt.Fscan(input, &STRING)

		// for i := 0; i < n; i++ {
		// 	fmt.Fscan(input, &XARRAY[i])
		// }

		k := p % a
		m := p % b
		h := p % c
		if k*m*h == 0 {
			fmt.Println(0)
		} else {
			aa := MIN(a-k, b-m)
			bb := MIN(aa, c-h)

			fmt.Println(bb)
		}

	}

}

/*
URL:
https://codeforces.com/contest/1492/problem/A
*/

package main

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

var (
	println = fmt.Println

	t          int
	p, a, b, c int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		p, a, b, c = readll4()

		solve()
	}
}

func solve() {
	var A, B, C int64
	A, B, C = 0, 0, 0
	if p%a != 0 {
		A = a - (p % a)
	}
	if p%b != 0 {
		B = b - (p % b)
	}
	if p%c != 0 {
		C = c - (p % c)
	}

	ans := min(A, B, C)
	printf("%d\n", ans)
}

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

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

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

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

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

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

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

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

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

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

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

// abs is integer version of math.Abs
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// pow is integer version of math.Pow
// pow calculate a power by Binary Power (二分累乗法(O(log e))).
func pow(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := pow(a, halfE)
		return half * half
	}

	return a * pow(a, e-1)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

	return res
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

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

	solve := func(Case int) {
		var p int64
		Fscan(in, &p)
		mi := int64(2e18)
		a := make([]int64, 3)
		for i := range a {
			Fscan(in, &a[i])
			x :=p%a[i]
			if x  > 0 {
				x= a[i]-x
			}
			mi = min(mi, x)
		}
		Fprintln(out, mi)

	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

func main() { run(os.Stdin, os.Stdout) }
func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

package main

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

func fastGetInt64(b []byte) int64 {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	n = 0
	for _, v := range b {
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func getDiff(a,p int64) int64{
	return a - (p%a)
}

func getMin(a,b int64) int64{

	if a < b{
		return a
	}
	return b
}

//========== Implement Algorithm =======================
func solution(p,a,b,c int64) int64 {

	if p%a == 0 || p%b == 0 || p%c == 0 {
		return 0
	}

	val := getMin(getDiff(a,p),math.MaxInt64)
	val = getMin(getDiff(b,p),val)
	val = getMin(getDiff(c,p),val)

	return val

}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var n, p, a, b, c  int64
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
		scanner.Scan()
		n = fastGetInt64(scanner.Bytes())
		for i := 0; i < int(n); i++ {
			scanner.Scan()
			p = fastGetInt64(scanner.Bytes())
			scanner.Scan()
			a = fastGetInt64(scanner.Bytes())
			scanner.Scan()
			b = fastGetInt64(scanner.Bytes())
			scanner.Scan()
			c = fastGetInt64(scanner.Bytes())
			fmt.Println(solution(p,a,b,c))
		}
	//======================================================

	//==================== OUTPUT ==========================

}

package main

import "fmt"

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

func timeToWait(a, p int64) int64 {
	mod := p % a
	if mod == 0 {
		return mod
	}
	return a - mod
}

func solve() int64 {
	var p, a, b, c int64
	fmt.Scan(&p, &a, &b, &c)
	return min(min(timeToWait(a, p), timeToWait(c, p)), timeToWait(b, p))
}

func main() {
	var testsCnt int
	fmt.Scan(&testsCnt)
	for i := 0; i < testsCnt; i++ {
		fmt.Println(solve())
	}
}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var tt int
	fmt.Fscanf(r, "%d\n", &tt)
	for tt > 0 {
		var a, b, c, p int64
		fmt.Fscanf(r, "%d %d %d %d\n", &p, &a, &b, &c)
		solve(p, a, b, c)
		tt--
	}

}

func solve(p, a, b, c int64) {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var A, B, C int64
	if p%a != 0 {
		A = a - (p % a)
	}
	if p%b != 0 {
		B = b - (p % b)
	}
	if p%c != 0 {
		C = c - (p % c)
	}
	// fmt.Fprintf(w, "hello")
	fmt.Fprintf(w, "%d\n", min(A, B, C))
	// fmt.Printf("%d\n", min(A, B, C))
}

func min(a ...int64) int64 {
	m := a[0]
	for _, v := range a {
		if v < m {
			m = v
		}
	}
	return m
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, min, p, a, b, c int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &p)
		Fscan(in, &a)
		Fscan(in, &b)
		Fscan(in, &c)
		if p%a != 0 {
			a = a * ((p / a) + 1)
		} else {
			a = a * (p / a)
		}
		if p%b != 0 {
			b = b * ((p / b) + 1)
		} else {
			b = b * (p / b)
		}
		if p%c != 0 {
			c = c * ((p / c) + 1)
		} else {
			c = c * (p / c)
		}
		min = a - p
		if b-p < min {
			min = b - p
		}
		if c-p < min {
			min = c - p
		}
		Fprintln(out, min)

	}
}

package main

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

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

	for Fscan(in, &T); T > 0; T-- {
		var p,a,b,c uint64
		Fscan(in, &p)
		Fscan(in, &a)
		Fscan(in, &b)
		Fscan(in, &c)

		ansA := ((p+a-1)/a) * a - p
		ansB := ((p+b-1)/b) * b - p
		ansC := ((p+c-1)/c) * c - p
		ans := ansA
		if ansB<ans{
			ans = ansB
		}
		if ansC<ans{
			ans=ansC
		}

		Fprintln(out, ans)

	}

}

package main
import(
    "fmt"
    "bufio"
    "os"
    "sort"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var x int
		fmt.Fscan(in,&x)
		list:= make([]int,3)
		for j:=0;j<3;j++{
			fmt.Fscan(in,&list[j])
			if list[j] < x {
				if x%list[j] == 0 {
					list[j]=x
				}else{
					list[j]*=(x/list[j]+1)
				}
			}
		}
		sort.Ints(list)
		fmt.Fprintln(out,list[0]-x)
	}
}

package main

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

func fastGetInt64(b []byte) int64 {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	n = 0
	for _, v := range b {
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func getDiff(a,b int64) int64{
	if a == b{
		return 0
	}
	if a > b{
		return a-b
	}
	return b-a
}

func getMin(a,b int64) int64{

	if a < b{
		return a
	}
	return b
}

//========== Implement Algorithm =======================
func solution(p,a,b,c int64) int64 {
	// var valA,valB,valC, count, tempVal int64
	// reached := true
	// finished := 0
	// count = 1
	// valA,valB,valC = math.MaxInt64, math.MaxInt64, math.MaxInt64
	// hitA,hitB,hitC := false,false,false
	// fmt.Println(p/b,"P")
	// for reached{

	// 	// count = p/a
	// 	if count*a >= p && !hitA {
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*a,p),valA)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*a,p),getDiff((count+1)*a,p))
	// 		}
	// 		// fmt.Println(tempVal,"A",count)
	// 		hitA = true
	// 		finished++
	// 		valA = getMin(tempVal,valA)
	// 	}
	// 	// count = p/b
	// 	if count*b >= p && !hitB{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*b,p),valB)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*b,p),getDiff((count+1)*b,p))
	// 		}
	// 		// fmt.Println(tempVal,"B")
	// 		hitB = true

	// 		finished++
	// 		valB = getMin(tempVal,valB)
	// 	}
	// 	// count = p/c
	// 	if count*c >= p && !hitC{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*c,p),valC)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*c,p),getDiff((count+1)*c,p))
	// 			fmt.Println(getDiff(count*c,p),"C",count)
	// 		}
	// 		hitC = true
	// 		finished++
	// 		valC = getMin(tempVal,valC)
	// 	}

	// 	if finished == 3{
	// 		reached = false
	// 	}

	// 	count ++
	// }2
	d := float64(p) / float64(a)
	valA := getMin(getDiff(p,int64(math.Ceil(d))*a),getDiff(p,(int64(math.Ceil(d))+1)*a))
	d = float64(p) / float64(b)
	valB := getMin(getDiff(p,int64(math.Ceil(d))*b),getDiff(p,(int64(math.Ceil(d))+1)*b))
	d = float64(p) / float64(c)
	valC := getMin(getDiff(p,int64(math.Ceil(d))*c),getDiff(p,(int64(math.Ceil(d))+1)*c))

	valA = getMin(valA,valB)
	valA = getMin(valA,valC)
	return valA

}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var n, p, a, b, c  int64
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
	scanner.Scan()
	n = fastGetInt64(scanner.Bytes())
	for i := 0; i < int(n); i++ {
		scanner.Scan()
		p = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		a = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		b = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		c = fastGetInt64(scanner.Bytes())
		fmt.Println(solution(p,a,b,c))
	}
	//======================================================

	//==================== OUTPUT ==========================

}

package main

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

func fastGetInt64(b []byte) int64 {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	n = 0
	for _, v := range b {
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func getDiff(a,b int64) int64{
	if a == b{
		return 0
	}
	if a > b{
		return a-b
	}
	return b-a
}

func getMin(a,b int64) int64{

	if a < b{
		return a
	}
	return b
}

//========== Implement Algorithm =======================
func solution(p,a,b,c int64) int64 {
	// var valA,valB,valC, count, tempVal int64
	// reached := true
	// finished := 0
	// count = 1
	// valA,valB,valC = math.MaxInt64, math.MaxInt64, math.MaxInt64
	// hitA,hitB,hitC := false,false,false
	// fmt.Println(p/b,"P")
	// for reached{

	// 	// count = p/a
	// 	if count*a >= p && !hitA {
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*a,p),valA)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*a,p),getDiff((count+1)*a,p))
	// 		}
	// 		// fmt.Println(tempVal,"A",count)
	// 		hitA = true
	// 		finished++
	// 		valA = getMin(tempVal,valA)
	// 	}
	// 	// count = p/b
	// 	if count*b >= p && !hitB{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*b,p),valB)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*b,p),getDiff((count+1)*b,p))
	// 		}
	// 		// fmt.Println(tempVal,"B")
	// 		hitB = true

	// 		finished++
	// 		valB = getMin(tempVal,valB)
	// 	}
	// 	// count = p/c
	// 	if count*c >= p && !hitC{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*c,p),valC)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*c,p),getDiff((count+1)*c,p))
	// 			fmt.Println(getDiff(count*c,p),"C",count)
	// 		}
	// 		hitC = true
	// 		finished++
	// 		valC = getMin(tempVal,valC)
	// 	}

	// 	if finished == 3{
	// 		reached = false
	// 	}

	// 	count ++
	// }
	d := float64(p) / float64(a)
	valA := getMin(getDiff(p,int64(math.Ceil(d))*a),getDiff(p,int64(math.Ceil(d))+1*a))
	d = float64(p) / float64(b)
	valB := getMin(getDiff(p,int64(math.Ceil(d))*b),getDiff(p,int64(math.Ceil(d))+1*b))
	d = float64(p) / float64(c)
	valC := getMin(getDiff(p,int64(math.Ceil(d))*c),getDiff(p,int64(math.Ceil(d))+1*c))

	valA = getMin(valA,valB)
	valA = getMin(valA,valC)
	return valA

}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var n, p, a, b, c  int64
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
	scanner.Scan()
	n = fastGetInt64(scanner.Bytes())
	for i := 0; i < int(n); i++ {
		scanner.Scan()
		p = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		a = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		b = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		c = fastGetInt64(scanner.Bytes())
		fmt.Println(solution(p,a,b,c))
	}
	//======================================================

	//==================== OUTPUT ==========================

}

package main

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

func fastGetInt64(b []byte) int64 {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	n = 0
	for _, v := range b {
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func getDiff(a,b int64) int64{
	if a == b{
		return 0
	}
	if a > b{
		return a-b
	}
	return b-a
}

func getMin(a,b int64) int64{

	if a < b{
		return a
	}
	return b
}

//========== Implement Algorithm =======================
func solution(p,a,b,c int64) int64 {
	// var valA,valB,valC, count, tempVal int64
	// reached := true
	// finished := 0
	// count = 1
	// valA,valB,valC = math.MaxInt64, math.MaxInt64, math.MaxInt64
	// hitA,hitB,hitC := false,false,false
	// fmt.Println(p/b,"P")
	// for reached{

	// 	// count = p/a
	// 	if count*a >= p && !hitA {
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*a,p),valA)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*a,p),getDiff((count+1)*a,p))
	// 		}
	// 		// fmt.Println(tempVal,"A",count)
	// 		hitA = true
	// 		finished++
	// 		valA = getMin(tempVal,valA)
	// 	}
	// 	// count = p/b
	// 	if count*b >= p && !hitB{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*b,p),valB)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*b,p),getDiff((count+1)*b,p))
	// 		}
	// 		// fmt.Println(tempVal,"B")
	// 		hitB = true

	// 		finished++
	// 		valB = getMin(tempVal,valB)
	// 	}
	// 	// count = p/c
	// 	if count*c >= p && !hitC{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*c,p),valC)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*c,p),getDiff((count+1)*c,p))
	// 			fmt.Println(getDiff(count*c,p),"C",count)
	// 		}
	// 		hitC = true
	// 		finished++
	// 		valC = getMin(tempVal,valC)
	// 	}

	// 	if finished == 3{
	// 		reached = false
	// 	}

	// 	count ++
	// }
	d := float64(p) / float64(a)
	valA := getMin(getDiff(p,int64(math.Ceil(d))*a),getDiff(p,int64(math.Ceil(d))-1*a))
	d = float64(p) / float64(b)
	valB := getMin(getDiff(p,int64(math.Ceil(d))*b),getDiff(p,int64(math.Ceil(d))-1*b))
	d = float64(p) / float64(c)
	valC := getMin(getDiff(p,int64(math.Ceil(d))*c),getDiff(p,int64(math.Ceil(d))-1*c))

	valA = getMin(valA,valB)
	valA = getMin(valA,valC)
	return valA

}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var n, p, a, b, c  int64
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
	scanner.Scan()
	n = fastGetInt64(scanner.Bytes())
	for i := 0; i < int(n); i++ {
		scanner.Scan()
		p = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		a = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		b = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		c = fastGetInt64(scanner.Bytes())
		fmt.Println(solution(p,a,b,c))
	}
	//======================================================

	//==================== OUTPUT ==========================

}

package main

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

func fastGetInt64(b []byte) int64 {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	n = 0
	for _, v := range b {
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func getDiff(a,b int64) int64{
	if a == b{
		return 0
	}
	if a > b{
		return a-b
	}
	return b-a
}

func getMin(a,b int64) int64{

	if a < b{
		return a
	}
	return b
}

//========== Implement Algorithm =======================
func solution(p,a,b,c int64) int64 {
	// var valA,valB,valC, count, tempVal int64
	// reached := true
	// finished := 0
	// count = 1
	// valA,valB,valC = math.MaxInt64, math.MaxInt64, math.MaxInt64
	// hitA,hitB,hitC := false,false,false
	// fmt.Println(p/b,"P")
	// for reached{

	// 	// count = p/a
	// 	if count*a >= p && !hitA {
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*a,p),valA)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*a,p),getDiff((count+1)*a,p))
	// 		}
	// 		// fmt.Println(tempVal,"A",count)
	// 		hitA = true
	// 		finished++
	// 		valA = getMin(tempVal,valA)
	// 	}
	// 	// count = p/b
	// 	if count*b >= p && !hitB{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*b,p),valB)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*b,p),getDiff((count+1)*b,p))
	// 		}
	// 		// fmt.Println(tempVal,"B")
	// 		hitB = true

	// 		finished++
	// 		valB = getMin(tempVal,valB)
	// 	}
	// 	// count = p/c
	// 	if count*c >= p && !hitC{
	// 		if count != 1{
	// 			tempVal = getMin(getDiff(count*c,p),valC)
	// 		}else{
	// 			tempVal = getMin(getDiff(count*c,p),getDiff((count+1)*c,p))
	// 			fmt.Println(getDiff(count*c,p),"C",count)
	// 		}
	// 		hitC = true
	// 		finished++
	// 		valC = getMin(tempVal,valC)
	// 	}

	// 	if finished == 3{
	// 		reached = false
	// 	}

	// 	count ++
	// }
	d := float64(p) / float64(a)
	valA := getDiff(p,int64(math.Ceil(d))*a)
	d = float64(p) / float64(b)
	valB := getDiff(p,int64(math.Ceil(d))*b)
	d = float64(p) / float64(c)
	valC := getDiff(p,int64(math.Ceil(d))*c)

	valA = getMin(valA,valB)
	valA = getMin(valA,valC)
	return valA

}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var n, p, a, b, c  int64
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
	scanner.Scan()
	n = fastGetInt64(scanner.Bytes())
	for i := 0; i < int(n); i++ {
		scanner.Scan()
		p = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		a = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		b = fastGetInt64(scanner.Bytes())
		scanner.Scan()
		c = fastGetInt64(scanner.Bytes())
		fmt.Println(solution(p,a,b,c))
	}
	//======================================================

	//==================== OUTPUT ==========================

}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())
	for t > 0 {
		scanner.Scan()
		str := strings.Split(scanner.Text(), " ")
		p, _ := strconv.Atoi(str[0])
		a, _ := strconv.Atoi(str[1])
		b, _ := strconv.Atoi(str[2])
		c, _ := strconv.Atoi(str[3])
		curr := 1000
		if p%a == 0 || p%b == 0 || p%c == 0 {
			fmt.Println("0")
			t--
			continue
		}
		if gg := a - p%a; gg < curr {
			curr = gg
		}
		if gg := c - p%c; gg < curr {
			curr = gg
		}
		if gg := b - p%b; gg < curr {
			curr = gg
		}

		fmt.Println(curr)
		t--
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, min, p, a, b, c int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &p)
		Fscan(in, &a)
		Fscan(in, &b)
		Fscan(in, &c)
		for a < p {
			a = a + a
		}
		for b < p {
			b = b + b
		}
		for c < p {
			c = c + c
		}
		min = a - p
		if b-p < min {
			min = b - p
		}
		if c-p < min {
			min = c - p
		}
		Fprintln(out, min)

	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, min, p, a, b, c int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &p)
		Fscan(in, &a)
		Fscan(in, &b)
		Fscan(in, &c)
		for a < p {
			a = a * 2
		}
		for b < p {
			b = b * 2
		}
		for c < p {
			c = c * 2
		}
		min = a - p
		if b-p < min {
			min = b - p
		}
		if c-p < min {
			min = c - p
		}
		Fprintln(out, min)

	}
}

package main

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

type CF1492A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1492A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1492A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1492A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1492A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1492A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1492A
Date: 25/11/21
User: epradere
URL: https://codeforces.com/problemset/problem/1492/A
Problem: CF1492A
**/
func (in *CF1492A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		p, a, b, c := in.NextInt64(), in.NextInt64(), in.NextInt64(), in.NextInt64()

		ans := a - (p % a)
		if ans == a {
			ans = 0
		}
		ans = Min(ans, b-(p%b))
		if ans == b {
			ans = 0
		}
		ans = Min(ans, c-(p%c))
		if ans == c {
			ans = 0
		}
		fmt.Println(ans)

	}

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

func NewCF1492A(r *bufio.Reader) *CF1492A {
	return &CF1492A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1492A(bufio.NewReader(os.Stdin)).Run()
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var p, a, b, c, t int

	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &p, &a, &b, &c)
		ans := findClass(p, a)
		ans = min(ans, findClass(p, b))
		ans = min(ans, findClass(p, c))
		fmt.Println(ans)
	}
}

func findClass(p, a int) int {
	remind := p % a
	if remind == 0 {
		return 0
	}
	return a - remind
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

package main

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

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func get(x, p int64) int64 {
	res := x - p
	if res < 0 {
		res = x*int64(math.Ceil(float64(p)/float64(x))) - p
	}
	return res
}
func solve() {
	p, a, b, c := getI(), getI(), getI(), getI()
	resA := get(a, p)
	resB := get(b, p)
	resC := get(c, p)
	out(nmin(resA, resB, resC))
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	for i := getI(); i > 0; i-- {
		solve()
	}
	out()
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(wr, f, a...)
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []int64 {
	ret := make([]int64, N)
	for i := range ret {
		ret[i] = getI()
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func nsort(data ...int64) {
	sort.Slice(data, func(i, j int) bool { return data[i] < data[j] })
}

func nsum(data ...int64) int64 {
	var res int64
	for _, n := range data {
		res += n
	}
	return res
}

func njoin(s ...int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int64, fn func(int64)) {
	for i := int64(0); i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

package main

import "fmt"

func main() {
	var nums,a,b,c,now int
	fmt.Scanln(&nums)
	for i := 0; i < nums; i++{
		fmt.Scanln(&now,&a,&b,&c)
		minWait := b
		if now % a == 0 || now % b == 0 || now % c == 0{
			fmt.Println(0)
			continue
		}
		a,b,c = a - (now % a),b - (now % b),c - (now % c)
		if a == 0 || a < b{
			minWait = a
		}else{
			minWait = b
		}
		if c == 0 || c < minWait{
			minWait = c
		}
		fmt.Println(minWait)
	}
}