#!/usr/bin/python

import sys
import math

primes = []
MAXN = 50000
hash = []

def prime_test(v):
    for i in xrange(2,int(math.sqrt(v))+1):
        if v % i == 0:
            return False
    return True

def calc(v, k):
    if k >= MAXN:
        if (k <= v):
            return 1
        else:
            return 0
    else:
        res = v / k
        for prime in primes:
            if prime >= k:
                break
            res -= calc(v/k, prime)
        return res

if __name__=="__main__":
    hash = [-1] * MAXN
    for i in xrange(2,MAXN):
        if hash[i] == -1:
            primes.append(i)
            hash[i] = len(primes)-1
            v = i * i
            while (v < MAXN):
                hash[v] = -2
                v += i
    a,b,k = [int(v) for v in sys.stdin.readline().split(' ')]
    if (k < MAXN and hash[k] == -2) or (k >= MAXN and (not prime_test(k))):
        print 0
    else:
        print calc(b,k) - calc(a-1,k)


n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")


n, m, i1, j1, i2, j2 = map(int, raw_input().split())
x = [abs(i1 - i2), abs(j1 - j2)]
x.sort()
if x[1] >= 5:
    print "Second"
elif x[0] <= 2:
    print "First"
else:
    if x[1] == 4:
        print "Second"
    else:
        print "First"


n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 2 or m > 2:
    print("Second")
elif n == 2 and m == 2:
    print("Second")
else:
    print("First")


import re
import sys

MOD = 2 ** 15
MOD2 = 2 * MOD

class X:
    def __init__(self, x):
        if isinstance(x, X):
            self.x = x.x
        else:
            self.x = x
    def __add__(self, other):
        return X((self.x + other.x + MOD2) % MOD)
    def __sub__(self, other):
        return X((self.x - other.x + MOD2) % MOD)
    def __mul__(self, other):
        return X((self.x * other.x) % MOD)
    def __div__(self, other):
        return X((sefl.x // other.x) % MOD)
    def __eq__(self, other):
        return self.x == other.x
    def __lt__(self, other):
        return self.x < other.x
    def __gt__(self, other):
        return self.x > other.x

#fin = open("input.txt", 'r')
#fout = open("output.txt", 'w')
fin = sys.stdin
fout = sys.stdout

fn = int(fin.readline())
text = "".join(fin.readlines())

text.replace(";", "\n")
text = text[text.find("{") + 1: text.find("}")]
text = re.sub(r"(\d+)", r"X(\1)", text)
text = ["     " + x.strip() for x in text.split("\n")]
text = "\n".join(text)
text = re.sub(r"(if.*?)(return.*)", r"\1: \2", text)
text = "def ff(n):\n" + text

exec(compile(text.strip(), "f**k", 'exec')

cache = {}
def f(n):
    return cache[n.x]

ans = -1
for i in range(0, MOD + 1):
    t = cache[i] = X(ff(X(i)))
    if t.x == fn:
      ans = i

print(ans)


import re
import sys

sys.setrecursionlimit(5000)

MOD = 2 ** 15
MOD2 = 2 * MOD

class X:
    def __init__(self, x):
        if isinstance(x, X):
            self.x = x.x
        else:
            self.x = x
    def __add__(self, other):
        return X(((self.x + other.x) % MOD + MOD) % MOD)
    def __sub__(self, other):
        return X(((self.x - other.x) % MOD + MOD) % MOD)
    def __mul__(self, other):
        return X(((self.x * other.x) % MOD + MOD) % MOD)
    def __div__(self, other):
        return X(((sefl.x // other.x) % MOD + MOD) % MOD)
    def __eq__(self, other):
        return self.x == other.x
    def __lt__(self, other):
        return self.x < other.x
    def __gt__(self, other):
        return self.x > other.x

#fin, fout = open("input.txt", 'r'), open("output.txt", 'w')
fin, fout = sys.stdin, sys.stdout

fn = int(fin.readline())
text = "".join(fin.readlines())
text = text.replace("\n", "")

text = text[text.find("{") + 1: text.find("}")]
text = re.sub(r"(\d+)", r"X(\1)", text)
text = re.sub(r"(if.*?)return", r"\1 : return", text)
text = re.sub(r"\s*([\(\)])\s*", r"\1", text)
text = "".join(text)
text = "".join("     " + x.strip() + "\n" for x in text.split(";"))
text = "def ff(n):\n" + text

exec(compile(text.strip(), "f**k", 'exec'))

cache = {}
def f(n):
    try:
        return cache[n.x]
    except KeyError:
        r = cache[n.x] = X(ff(n))
        return r

ans = -1
for i in range(0, MOD):
    t = cache[i] = X(ff(X(i))
    if t.x == fn:
      ans = i

print(ans)


import re,sys
class INT:
    def __init__(self,a):
        if isinstance(a,INT):
            self.v=a.v
        else:
            self.v=int(a)
    def __add__(self,a):
        return INT((self.v+a.v)&32767)
    def __sub__(self,a):
        return INT((self.v-a.v)&32767)
    def __mul__(self,a):
        return INT((self.v*a.v)&32767)
    def __div__(self,a):
        return INT((self.v/a.v)&32767)
    def __eq__(self,a):
        return self.v==a.v
    def __gt__(self,a):
        return self.v>a.v
    def __lt__(self,a):
        return self.v<a.v
    def __and__(self,a):
        return INT(self.v&a.v)
n=input()
s="".join(sys.stdin.readlines())
s=s.replace("\n","")
s=s.replace("{","")
s=s.replace("}","")
s=s.replace("int f(int n)","");
s=re.sub("([0-9]+)","INT(\\1)",s)
s="a=[-1]*33000\ndef f(n):\n\tn=INT(n);if(a[n.v]!=-1)return a[n.v];"+s
s=re.sub("return(.*?);","return INT(\\1);",s)
s=s.replace(";","\n\t")
s=s.replace("return",":return")
for i in xrange(10):
    s=s.replace("\t ","\t").replace("\t:","\t")
s+="\n"
s+="k=-1\nfor i in xrange(32768):\n\ta[i]=f(i).v\n\tif a[i]==n:\n\t\tk=i\nprint k"
exec s


#!/usr/bin/python
import re, sys
n = int (sys.stdin.readline ())
class MyInt (object):
	def __init__ (self, a):
		if isinstance (a, MyInt):
			self.v = a.v
		else:
			self.v = int (a)
	def val (self):
		return self.v
	def __add__ (self, a):
		return MyInt ((self.val () + a.val ()) & 32767)
	def __sub__ (self, a):
		return MyInt ((self.val () - a.val ()) & 32767)
	def __mul__ (self, a):
		return MyInt ((self.val () * a.val ()) & 32767)
	def __div__ (self, a):
		return MyInt ((self.val () / a.val ()) & 32767)
	def __eq__ (self, a):
		return self.val () == a.val ()
	def __gt__ (self, a):
		return self.val () > a.val ()
	def __lt__ (self, a):
		return self.val () < a.val ()
	def __and__ (self, a):
		return MyInt (self.val () & a)
s = ''.join (sys.stdin.readlines ())
s = s.replace ('\n', '')
s = s.replace ('{', '')
s = s.replace ('}', '')
s = re.sub ('([0-9]+)', 'MyInt (\\1)', s)
s = s.replace ('int f(int n)', \
 'a = [-1] * 32768\ndef f (n):\n\tglobal a;' + \
 'n = MyInt (n);if (a[n.val ()] != -1) return a[n.val ()];')
s = re.sub ('return(.*?);','return MyInt (\\1);', s)
s = s.replace (';', '\n\t')
s = s.replace ('return', ':return')
s = s.replace ('\t ', '\t')
s = s.replace ('\t:', '\t')
s = s.replace ('\t ', '\t')
s = s.replace ('\t:', '\t')
s = s.replace ('\t ', '\t')
s = s.replace ('\t:', '\t')
s = s.replace ('\t ', '\t')
s = s.replace ('\t:', '\t')
s = s.replace ('\t ', '\t')
s += '\n'
s += 'k = -1\n'
s += 'for i in range (32768):\n'
s += '\ta[i] = f (i).val () & 32767\n'
#s += 'for i in range (32768):\n'
#s += '\tprint \'%d: %d\' % (i, a[i])\n'
s += 'for i in range (32768):\n'
s += '\tif a[i] == n:\n'
s += '\t\tk = i\n'
s += 'print k\n'
#s += 'print n\n'
s = s.replace ('\t\n', '\n')
#print s
exec s


#!/usr/bin/python
import sys
n = int (sys.stdin.readline ())
s = ''.join (sys.stdin.readlines ())
s = s.replace ('\n', '')
s = s.replace ('{', '')
s = s.replace ('}', '')
s = s.replace ('int f(int n)', \
 'a = [-1] * 32768\ndef f (n):\n\tglobal a;if (a[n] != -1) return a[n];')
s = s.replace (';', '\n\t')
s = s.replace ('return', ':return')
s = s.replace ('\t:', '\t')
s += '\n'
s += 'k = -1\n'
s += 'for i in range (32768):\n'
s += '\ta[i] = f (i) & 32767\n'
#s += 'for i in range (32768):\n'
#s += '\tprint \'%d: %d\' % (i, a[i])\n'
s += 'for i in range (32768):\n'
s += '\tif a[i] == n:\n'
s += '\t\tk = i\n'
s += 'print k\n'
#s += 'print n\n'
s = s.replace ('\t\n', '\n')
#print s
exec s


#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018

@author: ernesto
'''

n, m = [int(x) for x in input().strip().split(" ")]

posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None

ops = []

if(m > 1):
    for _ in range(0, m):
        s, n_s = [x for x in input().strip().split(" ")]
        n = int(n_s)
        ops.append((s, n))
    for i in range(0, m):
        op, num = ops[i]
        cont = False
        if op == '+':
            cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
            posteriores.add(num)
        if op == '-':
            cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
            if num not in mencionados:
                anteriores.add(num)
                ultima_salida_inesperada = num
            posteriores.discard(num)
            ultimo_en_salir[num] &= not posteriores
        continuos[num] &= cont
        mencionados.add(num)
#    print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
    if not anteriores and not posteriores:
        assert ultima_salida_inesperada is None
        if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
            posibles_jefes_mencionados.add(ops[0][1])
    else:
        if not posteriores:
            assert ultima_salida_inesperada is not None
            posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
            assert len(posibles_jefes_filtrados) == 1
            assert posibles_jefes_filtrados[0] == ops[-1][1]
            posibles_jefes_mencionados.add(ops[-1][1])
        else:
            if not anteriores:
                assert ultima_salida_inesperada is None
                posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
#                print("posibles {}".format(posibles_jefes_filtrados))
                assert len(posibles_jefes_filtrados) == 1
                assert posibles_jefes_filtrados[0] == ops[0][1]
                posibles_jefes_mencionados.add(ops[0][1])
            else:
                assert ultima_salida_inesperada is not None
                posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores & posteriores))

#    print("posibles jefes menc {}".format(posibles_jefes_mencionados))
    posibles_jefes -= (mencionados - posibles_jefes_mencionados)

print(len(posibles_jefes))
if(len(posibles_jefes)):
    print(" ".join(map(str, sorted(posibles_jefes))))


#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018

@author: ernesto
'''

n, m = [int(x) for x in input().strip().split(" ")]

posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None

ops = []

if(m > 1):
    for _ in range(0, m):
        s, n_s = [x for x in input().strip().split(" ")]
        n = int(n_s)
        ops.append((s, n))
    for i in range(0, m):
        op, num = ops[i]
        cont = False
        if op == '+':
            cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
            posteriores.add(num)
        if op == '-':
            cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
            if num not in mencionados:
                anteriores.add(num)
                ultima_salida_inesperada = num
            posteriores.discard(num)
            ultimo_en_salir[num] &= not posteriores
        continuos[num] &= cont
        mencionados.add(num)
#    print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
    if not anteriores and not posteriores:
        assert ultima_salida_inesperada is None
        if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
            posibles_jefes_mencionados.add(ops[0][1])
    else:
        if not posteriores:
            assert ultima_salida_inesperada is not None
            posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
            assert len(posibles_jefes_filtrados) <= 1
            if(posibles_jefes_filtrados):
                assert posibles_jefes_filtrados[0] == ops[-1][1]
                posibles_jefes_mencionados.add(ops[-1][1])
        else:
            if not anteriores:
                assert ultima_salida_inesperada is None
                posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
#                print("posibles {}".format(posibles_jefes_filtrados))
                assert len(posibles_jefes_filtrados) <= 1
                if(posibles_jefes_filtrados):
                    assert posibles_jefes_filtrados[0] == ops[0][1]
                    posibles_jefes_mencionados.add(ops[0][1])
            else:
                assert ultima_salida_inesperada is not None
                posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores & posteriores))

#    print("posibles jefes menc {}".format(posibles_jefes_mencionados))
    posibles_jefes -= (mencionados - posibles_jefes_mencionados)

print(len(posibles_jefes))
if(len(posibles_jefes)):
    print(" ".join(map(str, sorted(posibles_jefes))))


#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
'''
Created on 13/09/2018

@author: ernesto
'''

n, m = [int(x) for x in input().strip().split(" ")]

posibles_jefes = set(range(1, n + 1))
anteriores = set()
posteriores = set()
continuos = [True] * (n + 1)
mencionados = set()
posibles_jefes_mencionados = set()
ultimo_en_salir = [True] * (n + 1)
ultima_salida_inesperada = None

ops = []

if(m > 1):
    for _ in range(0, m):
        s, n_s = [x for x in input().strip().split(" ")]
        n = int(n_s)
        ops.append((s, n))
    for i in range(0, m):
        op, num = ops[i]
        cont = False
        if op == '+':
            cont = not i or (ops[i - 1][0] == '-' and ops[i - 1][1] == num)
            posteriores.add(num)
        if op == '-':
            cont = i == m - 1 or (ops[i + 1][0] == '+' and ops[i + 1][1] == num)
            if num not in mencionados:
                anteriores.add(num)
                ultima_salida_inesperada = num
            posteriores.discard(num)
            ultimo_en_salir[num] &= not posteriores
        continuos[num] &= cont
        mencionados.add(num)
#    print("anteriores {} posteriores {} continuos {} ops {}".format(anteriores, posteriores, continuos, ops))
    if not anteriores and not posteriores:
        assert ultima_salida_inesperada is None
        if ops[0][0] == '+' and ops[-1][0] == '-' and ops[0][1] == ops[-1][1] and continuos[ops[0][1]] and ultimo_en_salir[ops[0][1]]:
            posibles_jefes_mencionados.add(ops[0][1])
    else:
        if not posteriores:
            assert ultima_salida_inesperada is not None
            posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x] and ultima_salida_inesperada == x, anteriores))
            assert len(posibles_jefes_filtrados) <= 1
            if(posibles_jefes_filtrados):
                assert posibles_jefes_filtrados[0] == ops[-1][1]
                posibles_jefes_mencionados.add(ops[-1][1])
        else:
            if not anteriores:
                assert ultima_salida_inesperada is None
                posibles_jefes_filtrados = list(filter(lambda x:continuos[x] and ultimo_en_salir[x], posteriores))
#                print("posibles {}".format(posibles_jefes_filtrados))
                assert len(posibles_jefes_filtrados) <= 1
                if(posibles_jefes_filtrados):
                    assert posibles_jefes_filtrados[0] == ops[0][1]
                    posibles_jefes_mencionados.add(ops[0][1])
            else:
                assert ultima_salida_inesperada is not None
#                print("continuos {}".format(continuos))
                posibles_jefes_mencionados = set(filter(lambda x:ultimo_en_salir[x] and continuos[x] and ultima_salida_inesperada == x, anteriores & posteriores))

#    print("posibles jefes menc {}".format(posibles_jefes_mencionados))
    posibles_jefes -= (mencionados - posibles_jefes_mencionados)

print(len(posibles_jefes))
if(len(posibles_jefes)):
    print(" ".join(map(str, sorted(posibles_jefes))))


def solve(k, grid):
    seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1)
    flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]

    m = {
        'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
        'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
        'C': 'l'*k + 'u' + 'r'*k + 'd',
        'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2),
        'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k,
        'G': 'FF',
    }

    [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0]
    st = 'r'*(2*k - j) + 'd'*(1 - i)

    for v in range(2, 4*k + 2):
        ct = flat.index(v)

        if ct >= 2:
            st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G'
            flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:]

        if ct >= 1:
            st += 'G'
            flat = flat[1:3] + flat[:1] + flat[3:]

        st += 'L'
        flat = flat[1:] + flat[:1]

    if flat[0] == 1: return st, m

def main():
    def get_line():
        return [0 if x == 'E' else int(x) for x in input().split()]

    for cas in range(int(input())):
        res = solve(int(input()), [get_line() for i in range(2)])
        if res is None:
            print('SURGERY FAILED')
        else:
            print('SURGERY COMPLETE')
            st, m = res
            print(st)
            for shortcut in m.items(): print(*shortcut)
            print('DONE')

main()


import sys

OP_CW1 = 'A'
OP_CW4 = 'B'
OP_CW16 = 'C'
OP_CCW = 'E'
OP_L = 'U'
OP_INV_L = 'V'
OP_R = 'W'
OP_INV_R = 'X'
OP_S = 'S'
OP_MOVE_LL1 = 'O'
OP_MOVE_LL4 = 'P'
OP_MOVE_LL16 = 'Q'
OP_MOVE_L_THROW = 'R'

def GetK(board): return len(board) // 4

def Slot(board, slotval=-1): return board.index(slotval)

def KS(board, slotval=-1): return GetK(board), Slot(board, slotval)

def Width(K): return K * 2 + 1

def PrintPermumation(head, board, slotval=None):
    K = GetK(board)
    W = Width(K)
    if slotval is None: slotval = K
    slot = Slot(board, slotval)
    print(head, '===', file=sys.stderr)
    tostr = lambda x: 'EE' if x == slotval else '%2d' % x
    for row in [board[:W], board[W:]]:
        print(' '.join(tostr(x) for x in row), file=sys.stderr)

def ApplyOps(board, seq, ops=None, slotval=-1):
    K, slot = KS(board, slotval)
    W = Width(K)
    for c in seq:
        if c == 'l':
            assert slot % W > 0, slot
            s1 = slot - 1
        elif c == 'r':
            assert slot % W + 1 < W, slot
            s1 = slot + 1
        elif c == 'd':
            assert slot % W in [0, K, K * 2], slot
            assert slot // W == 0
            s1 = slot + W
        elif c == 'u':
            assert slot % W in [0, K, K * 2], slot
            assert slot // W == 1
            s1 = slot - W
        else:
            s1 = None
        if s1 is not None:
            board[s1], board[slot] = board[slot], board[s1]
        else:
            P = ops[c]
            tmp = board[:]
            for i in range(len(board)): board[i] = tmp[P[i]]
        slot = Slot(board, slotval)

def LoopedView(board):
    K, slot = KS(board)
    W = Width(slot)
    assert slot == K
    def translate(x):
        if x == -1: return x
        if x <= W: return x - 1
        # W+1 -> 2W-2
        return 3 * W - 1 - x
    r = []
    for rng in [range(slot + 1, W), reversed(range(W, W * 2)), range(0, slot)]:
        for i in rng:
            r.append(translate(board[i]))
    return r

def Mod(x, m):
    x %= m
    if x < 0: x += m
    return x

def CanonicalizeView(view):
    i = view.index(0)
    view[:] = view[i:] + view[:i]

def ToPermutation(K, ops, seq):
    board = list(range(K * 4 + 2))
    ApplyOps(board, seq, ops, slotval=K)
    return board

def InitOps(K, debug=False):
    W = Width(K)
    ops = {}
    ops_codes = {}
    def ToP(seq): return ToPermutation(K, ops, seq)
    def Assign(rep, seq):
        ops[rep] = ToP(seq)
        ops_codes[rep] = seq

    Assign(OP_CW1, 'l' * K + 'd' + 'r' * (K * 2) + 'u' + 'l' * K)
    if debug: PrintPermumation('CW1', ops[OP_CW1])
    Assign(OP_CW4, OP_CW1 * 4)
    if debug: PrintPermumation('CW4', ops[OP_CW4])
    Assign(OP_CW16, OP_CW4 * 4)
    Assign(OP_CCW, OP_CW1 * (W * 2 - 2))
    if debug: PrintPermumation('CCW', ops[OP_CCW])

    Assign(OP_L, 'l' * K + 'd' + 'r' * K + 'u')
    if debug: PrintPermumation('L', ops[OP_L])
    Assign(OP_INV_L, OP_L * (K * 2))
    if debug: PrintPermumation('INV_L', ops[OP_INV_L])
    Assign(OP_R, 'r' * K + 'd' + 'l' * K + 'u')
    if debug: PrintPermumation('R', ops[OP_R])
    Assign(OP_INV_R, OP_R * (K * 2))
    if debug: PrintPermumation('INV_R', ops[OP_INV_R])

    Assign(OP_S, OP_INV_R + OP_INV_L + OP_R + OP_L)
    if debug: PrintPermumation('S', ops[OP_S])

    Assign(OP_MOVE_LL1, OP_CW1 + OP_S + OP_CW1)
    Assign(OP_MOVE_LL4, OP_MOVE_LL1 * 4)
    Assign(OP_MOVE_LL16, OP_MOVE_LL4 * 4)
    Assign(OP_MOVE_L_THROW, OP_S * 2 + OP_CW1)
    if debug:
        PrintPermumation('MOVE_LL', ops[OP_MOVE_LL1])
        PrintPermumation('MOVE_L_THROW', ops[OP_MOVE_L_THROW])
    return ops, ops_codes

def Solve(board, debug=False):
    ans = []
    K, slot = KS(board)
    W = Width(K)

    if slot % W < K:
        t = 'r' * (K - slot % W)
    else:
        t = 'l' * (slot % W - K)
    if slot // W == 1:
        t = t + 'u'
    ans.append(t)
    ApplyOps(board, t)
    slot = Slot(board)
    assert slot == K

    ops, ops_codes = InitOps(K)

    def ApplyMultipleOp(num, items):
        for k, op in reversed(items):
            while num >= k:
                num -= k
                ApplyOps(board, op, ops)
                ans.append(op)

    for k in range(1, W * 2 - 1):
        view = LoopedView(board)
        if debug: print('=' * 20, k, '\n', view, file=sys.stderr)
        num_cw = Mod(+(K * 2 - view.index(k)), len(view))
        CanonicalizeView(view)
        num_move = view.index(k) - k
        if debug: print(num_cw, num_move, file=sys.stderr)
        ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
        if debug: PrintPermumation('t', board, slotval=-1)
        ApplyMultipleOp(num_move // 2, [(1, OP_MOVE_LL1), (4, OP_MOVE_LL4), (16, OP_MOVE_LL16)])
        if debug: PrintPermumation('tt', board, slotval=-1)
        if num_move % 2 > 0:
            if k == W * 2 - 2: return False
            ApplyOps(board, OP_MOVE_L_THROW, ops)
            ans.append(OP_MOVE_L_THROW)
    view = LoopedView(board)
    num_cw = Mod(K * 3 + 1 - view.index(0), len(view))
    ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
    if debug: PrintPermumation('ttt', board, slotval=-1)
    f = 'r' * K + 'd'
    ApplyOps(board, f)
    ans.append(f)
    if debug: PrintPermumation('ttt', board, slotval=-1)

    print('SURGERY COMPLETE')
    print(''.join(ans))
    for k, v in ops_codes.items():
        print(k, v)
    print('DONE')
    return True

#ops = InitOps(11, debug=True)

#import random
#board = list(range(10 * 4 + 2))
#random.shuffle(board)
#print(board)
##board = [4, 35, 3, 15, 38, 1, 31, 7, 42, 26, 19, 27, 5, 11, 2, 33, 40, 16, 20, 12, 18, 24, 28, 6, 36, 22, 9, 29, 30, 43, 21, 10, 17, 0, 13, 8, 45, 25, 37, 32, 44, 14, 39, 34, 23, 41]
#if True:
#    board[board.index(0)] = -1
#    a = Solve(board, debug=True)
#    print(a, file=sys.stderr)
for _ in range(int(sys.stdin.readline())):
    sys.stdin.readline()
    tr = lambda s: -1 if s == 'E' else int(s)
    row1 = list(map(tr, sys.stdin.readline().split()))
    row2 = list(map(tr, sys.stdin.readline().split()))
    if not Solve(row1 + row2): print('SURGERY FAILED')


def flatten(grid):
    k = len(grid[0]) // 2
    seek = list(range(2*k + 2)) + list(range(2*k + 2, 4*k + 2))[::-1]
    return [seek[v] for v in grid[0] + grid[1][::-1] if v]

def solve(grid):
    grid = list(map(list, grid))
    k = len(grid[0]) // 2
    flat = flatten(grid)

    m = {
        'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',
        'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,
        'C': 'l'*k + 'u' + 'r'*k + 'd',
        'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2),
        'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k,
        'G': 'FF',
    }

    [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0]
    st = 'r'*(2*k - j) + 'd'*(1 - i)

    for v in range(2, 4*k + 2):
        ct = flat.index(v)

        if ct >= 2:
            st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G'
            flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:]

        if ct >= 1:
            st += 'G'
            flat = flat[1:3] + flat[:1] + flat[3:]

        st += 'L'
        flat = flat[1:] + flat[:1]

    if flat[0] == 1: return st, m

def main():
    def get_line():
        return [0 if x == 'E' else int(x) for x in input().split()]

    for cas in range(int(input())):
        k = int(input())
        grid = [get_line() for i in range(2)]
        assert all(len(row) == 2*k + 1 for row in grid)
        res = solve(grid)
        if res is None:
            print('SURGERY FAILED')
        else:
            print('SURGERY COMPLETE')
            st, m = res
            print(st)
            for shortcut in m.items(): print(*shortcut)
            print('DONE')

main()


import sys

OP_CW1 = 'A'
OP_CW4 = 'B'
OP_CW16 = 'C'
OP_CCW = 'E'
OP_L = 'U'
OP_INV_L = 'V'
OP_R = 'W'
OP_INV_R = 'X'
OP_S = 'S'
OP_MOVE_LL1 = 'O'
OP_MOVE_LL4 = 'P'
OP_MOVE_LL16 = 'Q'
OP_MOVE_L_THROW = 'R'

def GetK(board): return len(board) // 4

def Slot(board, slotval=-1): return board.index(slotval)

def KS(board, slotval=-1): return GetK(board), Slot(board, slotval)

def Width(K): return K * 2 + 1

def PrintPermumation(head, board, slotval=None):
    K = GetK(board)
    W = Width(K)
    if slotval is None: slotval = K
    slot = Slot(board, slotval)
    print(head, '===', file=sys.stderr)
    tostr = lambda x: 'EE' if x == slotval else '%2d' % x
    for row in [board[:W], board[W:]]:
        print(' '.join(tostr(x) for x in row), file=sys.stderr)

def ApplyOps(board, seq, ops=None, slotval=-1):
    K, slot = KS(board, slotval)
    W = Width(K)
    for c in seq:
        if c == 'l':
            assert slot % W > 0, slot
            s1 = slot - 1
        elif c == 'r':
            assert slot % W + 1 < W, slot
            s1 = slot + 1
        elif c == 'd':
            assert slot % W in [0, K, K * 2], slot
            assert slot // W == 0
            s1 = slot + W
        elif c == 'u':
            assert slot % W in [0, K, K * 2], slot
            assert slot // W == 1
            s1 = slot - W
        else:
            s1 = None
        if s1 is not None:
            board[s1], board[slot] = board[slot], board[s1]
        else:
            P = ops[c]
            tmp = board[:]
            for i in range(len(board)): board[i] = tmp[P[i]]
        slot = Slot(board, slotval)

def LoopedView(board):
    K, slot = KS(board)
    W = Width(slot)
    assert slot == K
    def translate(x):
        if x == -1: return x
        if x <= W: return x - 1
        # W+1 -> 2W-2
        return 3 * W - 1 - x
    r = []
    for rng in [range(slot + 1, W), reversed(range(W, W * 2)), range(0, slot)]:
        for i in rng:
            r.append(translate(board[i]))
    return r

def Mod(x, m):
    x %= m
    if x < 0: x += m
    return x

def CanonicalizeView(view):
    i = view.index(0)
    view[:] = view[i:] + view[:i]

def ToPermutation(K, ops, seq):
    board = list(range(K * 4 + 2))
    ApplyOps(board, seq, ops, slotval=K)
    return board

def InitOps(K, debug=False):
    W = Width(K)
    ops = {}
    ops_codes = {}
    def ToP(seq): return ToPermutation(K, ops, seq)
    def Assign(rep, seq):
        ops[rep] = ToP(seq)
        ops_codes[rep] = seq

    Assign(OP_CW1, 'l' * K + 'd' + 'r' * (K * 2) + 'u' + 'l' * K)
    if debug: PrintPermumation('CW1', ops[OP_CW1])
    Assign(OP_CW4, OP_CW1 * 4)
    if debug: PrintPermumation('CW4', ops[OP_CW4])
    Assign(OP_CW16, OP_CW4 * 4)
    Assign(OP_CCW, OP_CW1 * (W * 2 - 2))
    if debug: PrintPermumation('CCW', ops[OP_CCW])

    Assign(OP_L, 'l' * K + 'd' + 'r' * K + 'u')
    if debug: PrintPermumation('L', ops[OP_L])
    Assign(OP_INV_L, OP_L * (K * 2))
    if debug: PrintPermumation('INV_L', ops[OP_INV_L])
    Assign(OP_R, 'r' * K + 'd' + 'l' * K + 'u')
    if debug: PrintPermumation('R', ops[OP_R])
    Assign(OP_INV_R, OP_R * (K * 2))
    if debug: PrintPermumation('INV_R', ops[OP_INV_R])

    Assign(OP_S, OP_INV_R + OP_INV_L + OP_R + OP_L)
    if debug: PrintPermumation('S', ops[OP_S])

    Assign(OP_MOVE_LL1, OP_CW1 + OP_S + OP_CW1)
    Assign(OP_MOVE_LL4, OP_MOVE_LL1 * 4)
    Assign(OP_MOVE_LL16, OP_MOVE_LL4 * 4)
    Assign(OP_MOVE_L_THROW, OP_S * 2 + OP_CW1)
    if debug:
        PrintPermumation('MOVE_LL', ops[OP_MOVE_LL1])
        PrintPermumation('MOVE_L_THROW', ops[OP_MOVE_L_THROW])
    return ops, ops_codes

def Solve(board, debug=False):
    ans = []
    K, slot = KS(board)
    W = Width(K)

    if slot % W < K:
        t = 'r' * (K - slot % W)
    else:
        t = 'l' * (slot % W - K)
    if slot // W == 1:
        t = t + 'u'
    ans.append(t)
    ApplyOps(board, t)
    slot = Slot(board)
    assert slot == K

    ops, ops_codes = InitOps(K)

    def ApplyMultipleOp(num, items):
        for k, op in reversed(items):
            while num >= k:
                num -= k
                ApplyOps(board, op, ops)
                ans.append(op)

    for k in range(1, W * 2 - 1):
        view = LoopedView(board)
        if debug: print('=' * 20, k, '\n', view, file=sys.stderr)
        num_cw = Mod(+(K * 2 - view.index(k)), len(view))
        CanonicalizeView(view)
        num_move = view.index(k) - k
        if debug: print(num_cw, num_move, file=sys.stderr)
        ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
        if debug: PrintPermumation('t', board, slotval=-1)
        ApplyMultipleOp(num_move // 2, [(1, OP_MOVE_LL1), (4, OP_MOVE_LL4), (16, OP_MOVE_LL16)])
        if debug: PrintPermumation('tt', board, slotval=-1)
        if num_move % 2 > 0:
            if k == W * 2 - 2: return False
            ApplyOps(board, OP_MOVE_L_THROW, ops)
            ans.append(OP_MOVE_L_THROW)
    view = LoopedView(board)
    num_cw = Mod(K * 3 + 1 - view.index(0), len(view))
    ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
    if debug: PrintPermumation('ttt', board, slotval=-1)
    f = 'r' * K + 'd'
    ApplyOps(board, f)
    ans.append(f)
    if debug: PrintPermumation('ttt', board, slotval=-1)

    print('SURGERY COMPLETE')
    print(''.join(ans))
    for k, v in ops_codes.items():
        print(k, v)
    return True

#ops = InitOps(11, debug=True)

#import random
#board = list(range(10 * 4 + 2))
#random.shuffle(board)
#print(board)
##board = [4, 35, 3, 15, 38, 1, 31, 7, 42, 26, 19, 27, 5, 11, 2, 33, 40, 16, 20, 12, 18, 24, 28, 6, 36, 22, 9, 29, 30, 43, 21, 10, 17, 0, 13, 8, 45, 25, 37, 32, 44, 14, 39, 34, 23, 41]
#if True:
#    board[board.index(0)] = -1
#    a = Solve(board, debug=True)
#    print(a, file=sys.stderr)
for _ in range(int(sys.stdin.readline())):
    sys.stdin.readline()
    tr = lambda s: -1 if s == 'E' else int(s)
    row1 = list(map(tr, sys.stdin.readline().split()))
    row2 = list(map(tr, sys.stdin.readline().split()))
    if not Solve(row1 + row2): print('SURGERY FAILED')


import sys
input = sys.stdin.readline

n, m = map(int, input().split())
dp = [0] * (n + 2)
dp[n] = 1
for i in range(n - 1, 0, -1):
    dpi = dp[i + 1]
    j = 2
    while i * j < n + 2:
        dpi += dp[i * j] - dp[min(n + 1, (i + 1) * j)]
        dpi %= m
        j += 1
    dp[i] = dpi + dp[i + 1]
    dp[i] %= m
ans = (dp[1] - dp[2]) % m
print(ans)


import sys
import collections

infile = sys.stdin.buffer
def gs()  : return infile.readline().rstrip()
def gi()  : return int(gs())
def gss() : return gs().split()
def gis() : return [int(x) for x in gss()]

MOD = 10 ** 9 + 7
INF = 10 ** 12
N = 10 ** 5

def main(infn="") :
    global infile
    infile = open(infn,"r") if infn else open(sys.argv[1],"r") if len(sys.argv) > 1 else sys.stdin
    ######################################################################
    n,m = gis()
    dp = [0 for _ in range(n+1)]
    dp[1] = 1
    h = [0 for _ in range(n+1)]
    cumul = 0
    prev = dp[1]
    h[2]-=1
    for u in range(1, len(dp)):
        if u > 1:
            dp[u] += prev + dp[1]
            dp[u] %= m

            cumul += h[u]
            cumul %= m

            dp[u] += cumul
            dp[u] %= m

            prev += dp[u]
            prev %= m
        '''u = 7
        14 + 0, 14 + 1, 14 + 2
        7        7         8
        '''
        j = 2
        while( j * u < len(dp)):
            h[j*u] += dp[u]
            h[j*u] %= m
            if j*u + j< len(dp):
                h[j*u + j] -= dp[u]
                h[j*u + j] %= m
            j+=1
    print (dp[-1])

    ######################################################################
if __name__ == '__main__' :
    main()


def divisors(M):
    d=[]
    i=1
    while M>=i**2:
        if M%i==0:
            d.append(i)
            if i**2!=M:
                d.append(M//i)
        i=i+1
    return d

def popcount(x):
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    return x & 0x0000007f

def eratosthenes(n):
    res=[0 for i in range(n+1)]
    prime=set([])
    for i in range(2,n+1):
        if not res[i]:
            prime.add(i)
            for j in range(1,n//i+1):
                res[i*j]=1
    return prime

def factorization(n):
    res=[]
    for p in prime:
        if n%p==0:
            while n%p==0:
                n//=p
            res.append(p)
    if n!=1:
        res.append(n)
    return res

def euler_phi(n):
    res = n
    for x in range(2,n+1):
        if x ** 2 > n:
            break
        if n%x==0:
            res = res//x * (x-1)
            while n%x==0:
                n //= x
    if n!=1:
        res = res//n * (n-1)
    return res

def ind(b,n):
    res=0
    while n%b==0:
        res+=1
        n//=b
    return res

def isPrimeMR(n):
    d = n - 1
    d = d // (d & -d)
    L = [2, 3, 5, 7, 11, 13, 17]
    for a in L:
        t = d
        y = pow(a, t, n)
        if y == 1: continue
        while y != n - 1:
            y = (y * y) % n
            if y == 1 or t == n - 1: return 0
            t <<= 1
    return 1
def findFactorRho(n):
    from math import gcd
    m = 1 << n.bit_length() // 8
    for c in range(1, 99):
        f = lambda x: (x * x + c) % n
        y, r, q, g = 2, 1, 1, 1
        while g == 1:
            x = y
            for i in range(r):
                y = f(y)
            k = 0
            while k < r and g == 1:
                ys = y
                for i in range(min(m, r - k)):
                    y = f(y)
                    q = q * abs(x - y) % n
                g = gcd(q, n)
                k += m
            r <<= 1
        if g == n:
            g = 1
            while g == 1:
                ys = f(ys)
                g = gcd(abs(x - ys), n)
        if g < n:
            if isPrimeMR(g): return g
            elif isPrimeMR(n // g): return n // g
            return findFactorRho(g)
def primeFactor(n):
    i = 2
    ret = {}
    rhoFlg = 0
    while i*i <= n:
        k = 0
        while n % i == 0:
            n //= i
            k += 1
        if k: ret[i] = k
        i += 1 + i % 2
        if i == 101 and n >= 2 ** 20:
            while n > 1:
                if isPrimeMR(n):
                    ret[n], n = 1, 1
                else:
                    rhoFlg = 1
                    j = findFactorRho(n)
                    k = 0
                    while n % j == 0:
                        n //= j
                        k += 1
                    ret[j] = k

    if n > 1: ret[n] = 1
    if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
    return ret

def divisors(n):
    res = [1]
    prime = primeFactor(n)
    for p in prime:
        newres = []
        for d in res:
            for j in range(prime[p]+1):
                newres.append(d*p**j)
        res = newres
    res.sort()
    return res

def xorfactorial(num):
    if num==0:
        return 0
    elif num==1:
        return 1
    elif num==2:
        return 3
    elif num==3:
        return 0
    else:
        x=baseorder(num)
        return (2**x)*((num-2**x+1)%2)+function(num-2**x)

def xorconv(n,X,Y):
    if n==0:
        res=[(X[0]*Y[0])%mod]
        return res
    x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
    y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
    z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
    w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
    res1=xorconv(n-1,x,y)
    res2=xorconv(n-1,z,w)
    former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
    latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
    former=list(map(lambda x:x%mod,former))
    latter=list(map(lambda x:x%mod,latter))
    return former+latter

def merge_sort(A,B):
    pos_A,pos_B = 0,0
    n,m = len(A),len(B)
    res = []
    while pos_A < n and pos_B < m:
        a,b = A[pos_A],B[pos_B]
        if a < b:
            res.append(a)
            pos_A += 1
        else:
            res.append(b)
            pos_B += 1
    res += A[pos_A:]
    res += B[pos_B:]
    return res

class UnionFindVerSize():
    def __init__(self, N):
        self._parent = [n for n in range(0, N)]
        self._size = [1] * N
        self.group = N

    def find_root(self, x):
        if self._parent[x] == x: return x
        self._parent[x] = self.find_root(self._parent[x])
        stack = [x]
        while self._parent[stack[-1]]!=stack[-1]:
            stack.append(self._parent[stack[-1]])
        for v in stack:
            self._parent[v] = stack[-1]
        return self._parent[x]

    def unite(self, x, y):
        gx = self.find_root(x)
        gy = self.find_root(y)
        if gx == gy: return

        self.group -= 1

        if self._size[gx] < self._size[gy]:
            self._parent[gx] = gy
            self._size[gy] += self._size[gx]
        else:
            self._parent[gy] = gx
            self._size[gx] += self._size[gy]

    def get_size(self, x):
        return self._size[self.find_root(x)]

    def is_same_group(self, x, y):
        return self.find_root(x) == self.find_root(y)

class WeightedUnionFind():
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self.size = [1 for i in range(N)]
        self.val = [0 for i in range(N)]
        self.flag = True
        self.edge = [[] for i in range(N)]

    def dfs(self,v,pv):
        stack = [(v,pv)]
        new_parent = self.parent[pv]
        while stack:
            v,pv = stack.pop()
            self.parent[v] = new_parent
            for nv,w in self.edge[v]:
                if nv!=pv:
                    self.val[nv] = self.val[v] + w
                    stack.append((nv,v))

    def unite(self,x,y,w):
        if not self.flag:
            return
        if self.parent[x]==self.parent[y]:
            self.flag = (self.val[x] - self.val[y] == w)
            return

        if self.size[self.parent[x]]>self.size[self.parent[y]]:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[x] += self.size[y]
            self.val[y] = self.val[x] - w
            self.dfs(y,x)
        else:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[y] += self.size[x]
            self.val[x] = self.val[y] + w
            self.dfs(x,y)

class Dijkstra():
    class Edge():
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        self.G = [[] for i in range(V)]
        self._E = 0
        self._V = V

    @property
    def E(self):
        return self._E

    @property
    def V(self):
        return self._V

    def add_edge(self, _from, _to, _cost):
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        import heapq
        que = []
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost
                    heapq.heappush(que, (d[e.to], e.to))
        return d

#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
    N = len(s)
    Z_alg = [0]*N

    Z_alg[0] = N
    i = 1
    j = 0
    while i < N:
        while i+j < N and s[j] == s[i+j]:
            j += 1
        Z_alg[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < N and k + Z_alg[k]<j:
            Z_alg[i+k] = Z_alg[k]
            k += 1
        i += k
        j -= k
    return Z_alg

class BIT():
    def __init__(self,n,mod=0):
        self.BIT = [0]*(n+1)
        self.num = n
        self.mod = mod

    def query(self,idx):
        res_sum = 0
        mod = self.mod
        while idx > 0:
            res_sum += self.BIT[idx]
            if mod:
                res_sum %= mod
            idx -= idx&(-idx)
        return res_sum

    #Ai += x O(logN)
    def update(self,idx,x):
        mod = self.mod
        while idx <= self.num:
            self.BIT[idx] += x
            if mod:
                self.BIT[idx] %= mod
            idx += idx&(-idx)
        return

class dancinglink():
    def __init__(self,n,debug=False):
        self.n = n
        self.debug = debug
        self._left = [i-1 for i in range(n)]
        self._right = [i+1 for i in range(n)]
        self.exist = [True for i in range(n)]

    def pop(self,k):
        if self.debug:
            assert self.exist[k]
        L = self._left[k]
        R = self._right[k]
        if L!=-1:
            if R!=self.n:
                self._right[L],self._left[R] = R,L
            else:
                self._right[L] = self.n
        elif R!=self.n:
            self._left[R] = -1
        self.exist[k] = False

    def left(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._left[res]
            if res==-1:
                break
            k -= 1
        return res

    def right(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._right[res]
            if res==self.n:
                break
            k -= 1
        return res

class SparseTable():
    def __init__(self,A,merge_func,ide_ele):
        N=len(A)
        n=N.bit_length()
        self.table=[[ide_ele for i in range(n)] for i in range(N)]
        self.merge_func=merge_func

        for i in range(N):
            self.table[i][0]=A[i]

        for j in range(1,n):
            for i in range(0,N-2**j+1):
                f=self.table[i][j-1]
                s=self.table[i+2**(j-1)][j-1]
                self.table[i][j]=self.merge_func(f,s)

    def query(self,s,t):
        b=t-s+1
        m=b.bit_length()-1
        return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])

class BinaryTrie:
    class node:
        def __init__(self,val):
            self.left = None
            self.right = None
            self.max = val

    def __init__(self):
        self.root = self.node(-10**15)

    def append(self,key,val):
        pos = self.root
        for i in range(29,-1,-1):
            pos.max = max(pos.max,val)
            if key>>i & 1:
                if pos.right is None:
                    pos.right = self.node(val)
                    pos = pos.right
                else:
                    pos = pos.right
            else:
                if pos.left is None:
                    pos.left = self.node(val)
                    pos = pos.left
                else:
                    pos = pos.left
        pos.max = max(pos.max,val)

    def search(self,M,xor):
        res = -10**15
        pos = self.root
        for i in range(29,-1,-1):
            if pos is None:
                break

            if M>>i & 1:
                if xor>>i & 1:
                    if pos.right:
                        res = max(res,pos.right.max)
                    pos = pos.left
                else:
                    if pos.left:
                        res = max(res,pos.left.max)
                    pos = pos.right
            else:
                if xor>>i & 1:
                    pos = pos.right
                else:
                    pos = pos.left

        if pos:
            res = max(res,pos.max)
        return res

def solveequation(edge,ans,n,m):
    #edge=[[to,dire,id]...]
    x=[0]*m
    used=[False]*n
    for v in range(n):
        if used[v]:
            continue
        y = dfs(v)
        if y!=0:
            return False
    return x

    def dfs(v):
        used[v]=True
        r=ans[v]
        for to,dire,id in edge[v]:
            if used[to]:
                continue
            y=dfs(to)
            if dire==-1:
                x[id]=y
            else:
                x[id]=-y
            r+=y
        return r

class SegmentTree:
    def __init__(self, init_val, segfunc, ide_ele):
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        self.size = n
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        if r==self.size:
            r = self.num

        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

    def bisect_l(self,l,r,x):
        l += self.num
        r += self.num
        Lmin = -1
        Rmin = -1
        while l<r:
            if l & 1:
                if self.tree[l] <= x and Lmin==-1:
                    Lmin = l
                l += 1
            if r & 1:
                if self.tree[r-1] <=x:
                    Rmin = r-1
            l >>= 1
            r >>= 1

        if Lmin != -1:
            pos = Lmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        elif Rmin != -1:
            pos = Rmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        else:
            return -1

import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log

input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())

n,mod = mi()

M = int(n**.5) + 10

dp = [0 for i in range(n+1)]
imos = [0 for i in range(n+1)]
dp[1] = 1
for i in range(1,n):
    imos[i] = (imos[i] + imos[i-1]) % mod
    dp[i] += imos[i]
    dp[i] %= mod

    imos[i+1] += dp[i]
    imos[i+1] %= mod

    for j in range(2,n+1):
        if i*j > n:
            break

        imos[i*j] += dp[i]
        imos[i*j] %= mod
        if (i+1)*j <= n:
            imos[(i+1)*j] -= dp[i]
            imos[(i+1)*j] %= mod

    #print(dp)
    #print(imos)

    #debug = [dp[j] for j in range(n+1)]
    #S = imos[0]
    #for j in range(1,n+1):
        #S = (S + imos[j]) % mod
        #if i<j:
            #debug[j] += S
            #debug[j] %= mod

    #2~3
    #3~5
    #4~7
    #5~
    #print(debug)
    #print()

res = dp[n] + imos[n] + imos[n-1]
res %= mod
print(res)


# -*- coding: utf-8 -*-
"""
Created on Tue Aug 30 11:07:14 2022

@author: hp
"""

n,m = map(int,input().split())
sumL = [0]*(n+2)
L = 1
sumL[-2] = 1
for i in range(n-1,0,-1):
    L = sumL[i+1]
    j = 2
    while i*j<=n:
        L+=(sumL[i*j]-sumL[min(n,(i+1)*j-1)+1])
        L%=m
        j+=1
    L %= m
    sumL[i] = (sumL[i+1]+L)
    sumL[i]%=m
print(L)


import sys
input = lambda :sys.stdin.readline()[:-1]
ni = lambda :int(input())
na = lambda :list(map(int,input().split()))
yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES")
no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO")
#######################################################################
N, M = na()
mod = M
dp = [0]*(N+1)
dp[1] = 1
z = 1
for x in range(2,N+1):
    res, R = 0, x
    while R:
        q = x // R
        L = x // (q + 1)

        if q != x:
            res += dp[q] * (R - L)

            res %= mod
        R = L
    res += z
    res %= mod
    dp[x] = res
    z += dp[x]
    z %= mod
print(dp[N])


n, k = [int(item) for item in input().split()]
MOD = 10**9 + 7

MAX_N = 10**4

fac = [1] + [0] * MAX_N
fac_inv = [1] + [0] * MAX_N
for i in range(1, n+1):
    fac[i] = fac[i-1] * (i) % MOD
    # Fermat's little theorem says
    # a**(p-1) mod p == 1
    # then, a * a**(p-2) mod p == 1
    # it means a**(p-2) is inverse element
    fac_inv[i] = fac_inv[i-1] * pow(i, MOD-2, MOD) % MOD

def mod_nCr(n, r):
    if n == 0 and r == 0:
        return 1
    if n < r or n < 0:
        return 0
    tmp = fac_inv[n-r] * fac_inv[r] % MOD
    return tmp * fac[n] % MOD

ans = 0
total = pow(k, n*n, MOD)
for i in range(n+1):
    for j in range(n+1):
        not_one = (n - i + n - j) * n - ((n - i) * (n - j))
        free = n * n - not_one
        val = pow(-1, i+j) * mod_nCr(n, i) * mod_nCr(n, j) * pow(k-1, not_one, MOD) * pow(k, free, MOD)
        ans += val
        ans %= MOD

print(ans)


import sys
input = sys.stdin.readline

n,k=map(int,input().split())
mod=10**9+7

FACT=[1]
for i in range(1,2*10**5+1):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

def Combi(a,b):
    if 0<=b<=a:
        return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
    else:
        return 0

DP=[0]*(n+1)
DP[0]=1

for yoko in range(n):
    NDP=[0]*(n+1)
    for i in range(n+1):
        for j in range(max(1,i),n+1):
            PLUS=pow(k,i,mod)*Combi(n-i,j-i)*pow(k-1,n-j,mod)
            if i==j:
                PLUS-=pow(k-1,n,mod)

            #print(i,j,PLUS)
            NDP[j]=NDP[j]+DP[i]*PLUS

            NDP[j]%=mod

    DP=NDP
    #print(DP)

print(DP[-1])


import sys
input = sys.stdin.readline

n,k=map(int,input().split())
mod=10**9+7

FACT=[1]
for i in range(1,250+1):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(250,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

def Combi(a,b):
    if 0<=b<=a:
        return FACT[a]*FACT_INV[b]%mod*FACT_INV[a-b]%mod
    else:
        return 0

COMBI=[[0]*251 for i in range(251)]

for a in range(251):
    for b in range(a+1):
        COMBI[a][b]=Combi(a,b)

POW_K=[1]
POW_K1=[1]

for i in range(n+1):
    POW_K.append(POW_K[-1]*k%mod)
    POW_K1.append(POW_K1[-1]*(k-1)%mod)

DP=[0]*(n+1)
DP[0]=1

for yoko in range(n):
    NDP=[0]*(n+1)
    for i in range(n+1):
        if DP[i]==0:
            continue
        for j in range(max(1,i),n+1):

            if i==j:
                NDP[j]=(NDP[j]+(POW_K[i]*COMBI[n-i][j-i]%mod*POW_K1[n-j]%mod-POW_K1[n])%mod*DP[i]%mod)%mod

            else:
                NDP[j]=(NDP[j]+DP[i]*POW_K[i]%mod*COMBI[n-i][j-i]%mod*POW_K1[n-j]%mod)%mod

    DP=NDP
    #print(DP)

print(DP[-1])


import sys
input = sys.stdin.readline

n,k=map(int,input().split())
mod=10**9+7

FACT=[1]
for i in range(1,255+1):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(255,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

def Combi(a,b):
    if 0<=b<=a:
        return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
    else:
        return 0

COMBI=[[0]*255 for i in range(255)]

for i in range(255):
    for j in range(255):
        COMBI[i][j]=Combi(i,j)

POW_K=[1]
POW_K1=[1]

for i in range(255):
    POW_K.append(POW_K[-1]*k%mod)
    POW_K1.append(POW_K1[-1]*(k-1)%mod)

DP=[0]*(n+1)
DP[0]=1

for yoko in range(n):
    NDP=[0]*(n+1)
    for i in range(n+1):
        if DP[i]==0:
            continue
        for j in range(max(1,i),n+1):
            PLUS=POW_K[i]*COMBI[n-i][j-i]*POW_K1[n-j]
            if i==j:
                PLUS-=POW_K1[n]

            #print(i,j,PLUS)
            NDP[j]=NDP[j]+DP[i]*PLUS
            NDP[j]%=mod

    DP=NDP
    #print(DP)

print(DP[-1])


MOD = int(1e9+7)

def mult(l, r):
	return (l*r)%MOD

def fast_exp(b, e):
	if e == 0:
		return 1
	if e%2 == 1:
		return mult(b, fast_exp(b, e-1))
	else:
		b2 = fast_exp(b, e//2)
		return mult(b2, b2)

[n, k] = [int(s) for s in input().split(" ")]
print(n, k)
fact = (n+1)*[1]
for i in range(1, n+1):
	fact[i] = mult(i, fact[i-1])

ifact = (n+1)*[1]
ifact[n] = fast_exp(fact[n], MOD-2)
for i in reversed(range(1, n)):
	ifact[i] = mult(i+1, ifact[i+1])

def binom(N, K):
	return mult(mult(fact[N], ifact[K]), ifact[N-K])

def get(i, j):
	X = i*j
	Y = (n-i)*j
	Z = (n-j)*i
	tot = X+Y+Z
	ans = 0
	if (i+j)%2 == 0:
		ans = 1
	else:
		ans = (MOD - 1)
	ans = mult(ans, binom(n, j))
	ans = mult(ans, binom(n, i))
	ans = mult(ans, fast_exp(k, n*n - tot))
	ans = mult(ans, fast_exp(k-1, tot))
	return ans

ans = 0
for i in range(0, n+1):
	for j in range(0, n+1):
		ans = (ans + get(i, j)) % MOD

print(ans)


def gcd(a,b):
	if a%b == 0:
		return b
	else:
		return gcd(b,a%b)
s=raw_input().split()
a,h,w=int(s[0]),int(s[1]),int(s[2])
if(a>h)|(a>w):
	print-1
else:
	k=gcd(h+a,w+a)
	c=k//a
	if c==0:
		print-1
	else:
		print float(k)/c-a


a,h,w=(int(x) for x in input().split())
if h==w:
    if a<h:
        n=w//a
        x=(w-a*n)/(n+1)
        print(x)
    elif a==h:
        print(0)
    else:
        print(-1)
else:
    for i in range(100):
        if h>w:
            w,h=h,w
        if w>h+a*2:
            w=w-h-a
    if h>w:
        w,h=h,w
    m=h//a
    s=(w-h)//a
    r=0
    if m<s or s==0:
        for i in range(m,0,-1):
            x=(h-a*i)/(i+1)
            w1=w-x
            a1=a+x
            q=w1%a1
            if q<0.00000001 or a1-q<0.0000001:
                r=1
                break
        if r==0:
            print(-1)
        else:
            print(x)
    else:
        for i in range(s,0,-1):
            x=(w-h-i*a)/i
            w1=w-x
            a1=a+x
            q=w1%a1
            if q<0.00000001:
                r=1
                break
        if r==0:
            print(-1)
        else:
            print(x)


a,h,w=(int(x) for x in input().split())
for i in range(100):
    if h>w:
        w,h=h,w
    if w>h+a*2:
        w=w-h-a
if h>w:
    w,h=h,w
m=h//a
s=(w-h)//a
r=0
if m<s or s==0:
    for i in range(m,0,-1):
        x=(h-a*i)/(i+1)
        w1=w-x
        a1=a+x
        q=w1%a1
        if q<0.00000001 or a1-q<0.0000001:
            r=1
            break
    if r==0:
        print(-1)
    else:
        print(x)
else:
    for i in range(s,0,-1):
        x=(w-h-i*a)/i
        w1=w-x
        a1=a+x
        q=w1%a1
        if q<0.00000001:
            r=1
            break
    if r==0:
        print(-1)
    else:
        print(x)


a,h,w=(int(x) for x in input().split())
for i in range(100):
    if h>w:
        w,h=h,w
    if w>h+a*2:
        w=w-h-a
if h>w:
    w,h=h,w
m=h//a
s=(w-h)//a
r=0
if m<s or s==0:
    for i in range(m,0,-1):
        x=(h-a*i)/(i+1)
        w1=w-x
        a1=a+x
        q=w1%a1
        if q<0.00000001:
            r=1
            break
    if r==0:
        print(-1)
    else:
        print(x)
else:
    for i in range(s,0,-1):
        x=(w-h-i*a)/i
        w1=w-x
        a1=a+x
        q=w1%a1
        if q<0.00000001:
            r=1
            break
    if r==0:
        print(-1)
    else:
        print(x)


s=raw_input().split()
a,h,w=int(s[0]),int(s[1]),int(s[2])
if(a>h)|(a>w):
	print-1
else:
	k=abs(h-w)
	if k==0:
		k=h
	if k<a:
		print-1
	else:
		c=k//a
		print float(k)/c-a


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def readvars():
    k = map(int,input().split())
    return(k)

def readlist():
    li = list(map(int,input().split()))
    return(li)

def anslist(li):
    ans = " ".join([str(v) for v in li])
    return(ans)

def main():

    t = 1
#	t = int(input())

	for xx in range(t):
		n = readlist()
		for m in n: print(((((m//2) - (m//4) + 1)%(1000000007))*((m//4) + 1))%1000000007)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def readvars():
    k = map(int,input().split())
    return(k)

def readlist():
    li = list(map(int,input().split()))
    return(li)

def anslist(li):
    ans = " ".join([str(v) for v in li])
    return(ans)

def main():

    t = 1
#	t = int(input())

    for xx in range(t):
		n = readlist()
		for m in n: print(((((m//2) - (m//4) + 1)%(1000000007))*((m//4) + 1))%1000000007)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import atexit, io, sys

buffer = io.BytesIO()
sys.stdout = buffer

@atexit.register
def write():
    sys.__stdout__.write(buffer.getvalue())

n = int(raw_input())
m = raw_input().split()
for x in m:
	x = int(x)
	print( (((((x+4)//2)**2)//4)%1000000007) )


import sys
import atexit, io
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write():
    sys.__stdout__.write(buffer.getvalue())
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
t=sys.stdin.readline()
arr = get_ints()
for n in arr:
	# print(n)
	ans=((((n+4)//2)**2)//4)%1000000007
	print(ans)


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def readvars():
    k = map(int,input().split())
    return(k)

def readlist():
    li = list(map(int,input().split()))
    return(li)

def anslist(li):
    ans = " ".join([str(v) for v in li])
    return(ans)

def main():

    t = 1
#	t = int(input())

    for xx in range(t):
        t = int(input())
        n = readlist()
        for m in n: print(((((m//2) - (m//4) + 1)%(1000000007))*((m//4) + 1))%1000000007)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [-1]*n
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u] = v
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
ansv = 0
ans1 = 0
for v in range(k-1):
    if ans[way[v]] or  a[way[v]]!= way[v+1]:#
        ansv +=1
for v in range(k-1):
    if k-v-1!=lvl[way[v]]:
        ans1+=1
    else:
        break
print(ans1,ansv)


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0

for v in range(k-1):
    if ans[way[v]] or  len(a[way[v]])>1:#
        ansv +=1
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
print(ans1,ansv)


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0
for v in range(k-1):
    if ans[way[v]] or  a[way[v]].pop()!=way[v+1]:#
        ansv +=1
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
print(ans1,ansv)


import sys
from collections import deque
input = lambda : sys.stdin.readline().strip()
# for i in range(int(input())):
n,m = map(int,input().split())
g = {}
for i in range(m):
    a,b = map(int,input().split())
    if b-1 in g:
        g[b-1].append(a-1)
    else:
        g[b-1]=[a-1]
k = int(input())
way = list(map(lambda x: int(x)-1,input().split()))
bfs = deque()
bfs.append(way[-1])
lvl = [-1]*n
ans = [0]*n
a = [set() for j in range(n)]
lvl[way[-1]]=0
while bfs:
    v = bfs.popleft()
    for u in g[v]:
        if lvl[u]==-1:
            lvl[u]=lvl[v]+1
            a[u].add(v)
            bfs.append(u)
        elif lvl[u]==lvl[v]+1:
            ans[u]=1
            a[u].add(v)
ansv = 0
ans1 = 0
for v in range(k-1):
    if k-v-1!=lvl[way[v]] and way[v+1] not in a[way[v]]:
        ans1+=1
    elif k-v-1 == lvl[way[v]]:
        break
for v in range(k-1):
    if ans[way[v]] or  a[way[v]].pop()!=way[v+1]:#
        ansv +=1

print(ans1,ansv)


n, m = map(int, input().split())
prev_points = [[] for _ in range(n)]
for _ in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    prev_points[v].append(u)
k = int(input())
p = [int(pi) - 1 for pi in input().split()]
best_ways_d = [-1] * n
best_ways_nm1 = [0] * n
q = [(p[-1], 0)]
for u, d in q:
    if best_ways_d[u] < 0:
        best_ways_d[u] = d
        d += 1
        for v in prev_points[u]:
            q.append((v, d))
    elif best_ways_d[u] == d:
        best_ways_nm1[u] += 1
ans1 = ans2 = 0
for i in range(1, k):
    u, v = p[i - 1], p[i]
    if best_ways_d[u] <= best_ways_d[v]:
        ans1 += 1
        ans2 += 1
    elif best_ways_nm1[u]:
        ans2 += 1
print(ans1, ans2)


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp=[list() for _ in range(n+1)]
for i in range(2,n+1):
    p[i]=int(nums[i-2])

    mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if len(mp[i])>0:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]:
            return True
        for j in range(des-val,-1,-1):
            if v[j]:
                v[j+val]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp=[list() for _ in range(n+1)]
for i in range(2,n+1):
    p[i]=int(nums[i-2])

    mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if len(mp[i])>0:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]:
            return True
        for j in range(des-val,-1,-1):
            if  v[j] :
                v[j+val]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp=[list() for _ in range(n+1)]
for i in range(2,n+1):
    p[i]=int(nums[i-2])

    mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if len(mp[i])>0:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]:
            return True
        for j in range(des,val-1,-1):
            if v[j-val] and not v[j]:
                v[j]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp={}
for i in range(2,n+1):
    p[i]=int(nums[i-2])
    if p[i] in mp:
        mp[p[i]].append(i)
    else:
        mp[p[i]]=[i]
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if i in mp:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]==True:
            return True
        for j in range(des-val,-1,-1):
            if v[j]==True:
                v[j+val]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


n=int(input())
nums=input().split(' ')
l=[0]*4
for i in range(4):
    l[i]=int(nums[i])
t=tuple(l)
a,b,c,d=t
p=[0]*(n+1)
nums=input().split(' ')
mp=[[list()] for _ in range(n+1)]
for i in range(2,n+1):
    p[i]=int(nums[i-2])

    mp[p[i]].append(i)
s=[0]*(n+1)
def sof(i):
    if s[i]!=0:
        return s[i]
    if i in mp:
        res=0
        for son in mp[i]:
            res+=sof(son)
        s[i]=res
        return res
    else:
        s[i]=1
        return 1
rootofl=list()
for leaf in l:
    while p[leaf]!=1:
        leaf=p[leaf]
    rootofl.append(leaf)
rootlist=list()
for rootson in mp[1]:
    if not rootson in rootofl:
        rootlist.append(rootson)
def canpick(a,des):
    if des==0:
        return True
    picklist=rootlist[:]
    for j in range(2):
        cur=a[j]
        while p[cur]!=1:
            fa=p[cur]
            for i in mp[fa]:
                if i!=cur :
                    picklist.append(i)
            cur=fa
    v=[False]*(n+1)
    v[0]=True
    for i in range(len(picklist)):
        val=sof(picklist[i])
        if des-val>=0 and v[des-val]:
            return True
        for j in range(des-val,-1,-1):
            if v[j]:
                v[j+val]=True
    return False

m=sof(1)
if m%2==1:
    print('NO')
else:
    v1=m//2-1-sof(rootofl[2])
    v2=m//2-1-sof(rootofl[0])
    if canpick([a,b], v1) and canpick([c,d], v2):
        print('YES')
    else:
        print('NO')


start = raw_input().strip()
end = raw_input().strip()
k = int(raw_input())
if k == 0:
    if start == end:
       print 1
    else:
       print 0
    exit(0)
L = len(start)
ans = tmp = 0
mod = 10 ** 9 + 7
for i in xrange(1, L):
    if start[i:] + start[:i] == end:
        tmp += 1
if start == end:
    p = [1, 0]
    for i in xrange(k):
        p = [p[1], (p[0] * (L-1) + p[1] * (L-2)) % mod]
    ans += p[0]
if tmp > 0:
    p = [0, 1]
    for i in xrange(k):
        p = [p[1], (p[0] * (L-1) + p[1] * (L-2)) % mod]
    ans += p[0] * tmp % mod
print ans % mod


'''
Created on Apr 20, 2012

@author: Tobias Flach
'''

def solve():
    prime = 1000000007

    str_a = raw_input()
    str_b = raw_input()
    k = int(raw_input())

    good_shifts = 0
    bad_shifts  = 0

    for i in range(0, len(str_a)):
        shifted = str_a[i:] + str_a[:i]
        if shifted == str_b:
            good_shifts += 1
        else:
            bad_shifts += 1

    good_sols = 0
    bad_sols  = 0
    if str_a == str_b:
        good_sols = 1
    else:
        bad_sols  = 1

    for i in range(0, k):
        t_good_sols = good_sols * (good_shifts - 1) + bad_sols * good_shifts
        t_bad_sols  = good_sols * bad_shifts + bad_sols * (bad_shifts - 1)
        good_sols = t_good_sols % prime
        bad_sols  = t_bad_sols % prime

    print "%d" % (good_sols)

if __name__ == '__main__':
    solve()


import sys

start = raw_input()
end = raw_input()
k = int(raw_input())

dpA = [-1 for i in xrange(k+1)]
dpB = [-1 for i in xrange(k+1)]

def calculaA(n):
    global dpA, dpB
    if n == 0:
        return 0
    if dpA[n-1] == -1:
        calculaA(n-1)

    dpA[n] = dpA[n-1]*(A-1) + dpB[n-1]*A
    dpB[n] = dpA[n-1]*B     + dpB[n-1]*(B-1)

    return dpA[n]

if start == end and k == 0:
    print 1
    exit(0)

A = B = 0

if start != end:
    dpA[0] = 0
    dpB[0] = 1
else:
    dpA[0] = 1
    dpB[0] = 0

for i in xrange(len(start)):
    now = start[i:]+start[:i]

    if now == end:
        A += 1
    else:
        B += 1

print calculaA(k)


# Shayenne Moura

n, m, l = map(int, raw_input().split())

planet = []

for i in xrange(n):
    nome = raw_input()
    op = []
    for j in xrange(m):

        a, b, c = map(int, raw_input().split())

        op.append([a, b, c])

    planet.append(op)

maximo = 0

for i in xrange(n):
    for j in xrange(n):
        if i != j:
            pft = []
            for k in xrange(m):
                luc = planet[j][k][1] - planet[i][k][0]
                pft.append([luc, planet[i][k][2]])

            pft.sort(reverse=True, key=lambda tup:tup[0])

            qtd = 0
            ganho = 0
            for r in xrange(len(pft)):
                if qtd + pft[r][1] <= l and pft[r][0] > 0:
                    ganho += pft[r][0]*pft[r][1]
                    qtd += pft[r][1]
                elif pft[r][0] > 0:
                    ganho += pft[r][0]*(l-qtd)
                    break

            if ganho > maximo:
                maximo = ganho

print maximo


start = raw_input()
end = raw_input()
k = int(raw_input())

dpA = [-1 for i in xrange(k+1)]
dpB = [-1 for i in xrange(k+1)]

def calculaA(n):
    global dpA, dpB
    if n == 0:
        return 0
    if dpA[n-1] == -1:
        calculaA(n-1)

    dpA[n] = dpA[n-1]*(A-1) + dpB[n-1]*A
    dpB[n] = dpA[n-1]*B     + dpB[n-1]*(B-1)

    return dpA[n]

A = B = 0

if start != end:
    dpA[0] = 0
    dpB[0] = 1
else:
    dpA[0] = 1
    dpB[0] = 0

for i in xrange(len(start)):
    now = start[i:]+start[:i]

    if now == end:
        A += 1
    else:
        B += 1

print calculaA(k)


n = int(input())
f = list(map(int, input().split()))
for i in range(n):
    f[i] -= 1

def gcd(a, b):
    while (a != 0 and b != 0):
        a, b = b, a % b
    return a + b

def lcm(a, b):
    return a * b // gcd(a, b)

ans = 1
minn = 0

for i in range(n):
    vis = [False] * n
    cur = i
    st, pr = 0, 0
    while not vis[cur]:
        vis[cur] = True
        cur = f[cur]
        st += 1
    fs = cur
    cur = i
    while cur != fs:
        pr += 1
        cur = f[cur]
    minn = max(minn, pr)
    ans = lcm(ans, st - pr)

print(((max(0, minn - 1))// ans + 1) * ans)


import sys

n = int(sys.stdin.readline())
a = list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

path_lens = []
cycle_lens = []
for i, v in enumerate(a):
	cur = i
	visited = []
	while cur not in visited:
		visited.append(cur)
		cur = a[cur]
	visited.append(cur)

	path_len = 0
	for j, x in enumerate(visited):
		if x in visited[j+1:]:
			break
		path_len += 1
	cycle_len = len(visited) - path_len - 1

	path_lens.append(path_len)
	cycle_lens.append(cycle_len)

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

to_start = max(path_lens)
lcm = 1
for i, v in enumerate(cycle_lens):
	lcm = lcm * v // gcd(lcm, v)

# res = to_start
# if lcm > 1:
# 	res += lcm

res = to_start
if to_start % lcm > 0 or to_start == 0:
	res += lcm - to_start % lcm
print(res)


N = int(raw_input())
a = map(int, raw_input().split())
for i in xrange(N):
    a[i] -= 1

def pers(i):
    b = [-1] * N
    j = 0
    while b[i] == -1:
        b[i] = j
        i = a[i]
        j += 1
    return (b[i], j - b[i])

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return a / gcd(a, b) * b

x = 1
l = 1
for i in xrange(N):
    pred, per = pers(i)
    x = lcm(x, per)
    if pred > l:
        l = pred
y = x
while y < l:
    y += x
print y


n=int(input())
a=list(map(int, input().split()))

for i in range(len(a)):
    a[i] = a[i]-1

instack=[False]*n
processed=[False]*n
loopl = []
inloop = [False]*n
def dfs1(v):
    if (instack[v]):
        cl = 1
        t = a[v]
        inloop[v] = True
        while t != v:
            inloop[t] = True
            cl = cl+1
            t = a[t]
        loopl.append(cl)
        return
    if processed[v]:
        return

    processed[v] = True
    instack[v] = True
    dfs1(a[v])
    instack[v] = False
for i in range(n):
    dfs1(i)
maxdis = 0
for i in range(n):
    t = i
    cl = 0
    while not inloop[t]:
        cl += 1
        t = a[t]
    maxdis = max(maxdis, cl)

def gcd(a, b):
    if a == 0:
        return b
    return gcd(b%a, a)
def mkd(a, b):
    return (a*b)//gcd(a,b)
mkl=1
for i in loopl:
    mkl = mkd(mkl, i)
ans = mkl
while ans < maxdis:
    ans += mkl
print(ans)
#print(inloop)
#print(loopl)


from fractions import gcd

n = int(raw_input())
f = [0] + map(int, raw_input().split())

max_prefix = 0
period = 1

visited = set()
for i in xrange(1, n+1):
	if i not in visited:
		j, steps = i, 0
		while j not in visited:
			visited.add(j)
			j = f[j]
			steps += 1
		k, prefix = i, 0
		while k != j:
			k = f[k]
			prefix += 1
		max_prefix = max(max_prefix, prefix)
		loop = steps - prefix
		if loop:
			period = period * loop / gcd(period, loop)

p = period
while period < max_prefix:
	period += p
print period


import sys,heapq

#sys.stdin=open("data.txt")

input=sys.stdin.readline

n,a,b=map(int,input().split())

if a<b: a,b=b,a

if b==0:

    # 1 01 001 0001 ... is optimal, plus a long series of 0's

    print((n-1)*a)

else:

    # pascal's triangle thing

    pascal=[[1]*20005]

    for i in range(20004):

        newrow=[1]

        for j in range(1,20005):

            newrow.append(newrow[-1]+pascal[-1][j])

            if newrow[-1]>n: break

        pascal.append(newrow)

    def getcom(a,b):

        # return a+b choose b

        # if larger than n, return infinite

        if len(pascal[a])>b: return pascal[a][b]

        if b==0: return 1

        if b==1: return a

        return 100000005

    # start with the null node (prefix cost 0)

    # can split a node into two other nodes with added cost c+a+b

    # new nodes have prefix costs c+a, c+b

    # want n-1 splits in total

    remain=n-1

    ans=0

    possible=[[a+b,1]]    # [c,count]

    while 1:

        # cost u, v leaves

        u,v=heapq.heappop(possible)

        while possible and possible[0][0]==u:

            v+=possible[0][1]

            heapq.heappop(possible)

        if remain<=v:

            ans+=u*remain

            break

        ans+=u*v

        remain-=v

        heapq.heappush(possible,[u+a,v])

        heapq.heappush(possible,[u+b,v])

    print(ans)

# Made By Mostafa_Khaled


import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n,a,b=map(int,input().split())

if a<b: a,b=b,a

if b==0:
    # 1 01 001 0001 ... is optimal, plus a long series of 0's
    print((n-1)*a)
else:
    # pascal's triangle thing
    pascal=[[1]*20005]
    for i in range(20004):
        newrow=[1]
        for j in range(1,20005):
            newrow.append(newrow[-1]+pascal[-1][j])
            if newrow[-1]>n: break
        pascal.append(newrow)
    def getcom(a,b):
        # return a+b choose b
        # if larger than n, return infinite
        if len(pascal[a])>b: return pascal[a][b]
        if b==0: return 1
        if b==1: return a
        return 100000005

    # start with the null node (prefix cost 0)
    # can split a node into two other nodes with added cost c+a+b
    # new nodes have prefix costs c+a, c+b
    # want n-1 splits in total
    remain=n-1
    ans=0
    possible=[[a+b,1]]    # [c,count]
    while 1:
        # cost u, v leaves
        u,v=heapq.heappop(possible)
        while possible and possible[0][0]==u:
            v+=possible[0][1]
            heapq.heappop(possible)
        if remain<=v:
            ans+=u*remain
            break
        ans+=u*v
        remain-=v
        heapq.heappush(possible,[u+a,v])
        heapq.heappush(possible,[u+b,v])
    print(ans)


import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n,a,b=map(int,input().split())

if a<b: a,b=b,a

if b==0:
    # 1 01 001 0001 ... is optimal, plus a long series of 0's
    print((n-1)*a)
else:
    # pascal's triangle thing
    pascal=[[1]*20005]
    for i in range(20004):
        newrow=[1]
        for j in range(1,20005):
            newrow.append(newrow[-1]+pascal[-1][j])
            if newrow[-1]>n: break
        pascal.append(newrow)
    def getcom(a,b):
        # return a+b choose b
        # if larger than n, return infinite
        if len(pascal[a])>b: return pascal[a][b]
        if b==0: return 1
        if b==1: return a
        return 100000005

    # start with the null node (prefix cost 0)
    # can split a node into two other nodes with added cost c+a+b
    # new nodes have prefix costs c+a, c+b
    # want n-1 splits in total
    n-=1    # now represents number of splits needed

    # binary search the last cost added
    lo=0
    hi=a*int((n**0.5)*2+5)

    while 1:
        mid=(lo+hi)//2
        # count stuff
        c0=0    # < mid
        c1=0    # = mid
        for i in range(mid//a+1):
            j=(mid-i*a)//b
            if (mid-i*a)%b!=0:
                # c0 += iC0 + (i+1)C1 + (i+2)C2 + ... + (i+j)Cj
                for k in range(j+1):
                    #print(mid,i,k)
                    c0+=getcom(i,k)
                    if c0>n: break
            else:
                for k in range(j):
                    #print(mid,i,k)
                    c0+=getcom(i,k)
                    if c0>n: break
                #print(mid,i,j,"c1")
                c1+=getcom(i,j)
        #print(mid,"is",c0,c1)
        if n<c0:
            hi=mid-1
        elif c0+c1<n:
            lo=mid+1
        else:
            # mid is correct cutoff
            lowcost=0   # sum of all cost, where cost < mid
            for i in range(mid//a+1):
                j=(mid-i*a)//b
                if (mid-i*a)%b!=0:
                    for k in range(j+1):
                        lowcost+=getcom(i,k)*(i*a+k*b)
                else:
                    for k in range(j):
                        lowcost+=getcom(i,k)*(i*a+k*b)
            temp=lowcost+(n-c0)*mid
            print(temp+n*(a+b))
            break


import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n,a,b=map(int,input().split())

if a<b: a,b=b,a

if b==0:
    # 1 01 001 0001 ... is optimal
    print(n*a)
else:
    # pascal's triangle thing
    pascal=[[1]*20005]
    for i in range(20004):
        newrow=[1]
        for j in range(1,20005):
            newrow.append(newrow[-1]+pascal[-1][j])
            if newrow[-1]>n: break
        pascal.append(newrow)
    def getcom(a,b):
        # return a+b choose b
        # if larger than n, return infinite
        if len(pascal[a])>b: return pascal[a][b]
        if b==0: return 1
        if b==1: return a
        return 100000005

    # start with the null node (prefix cost 0)
    # can split a node into two other nodes with added cost c+a+b
    # new nodes have prefix costs c+a, c+b
    # want n-1 splits in total
    n-=1    # now represents number of splits needed

    # binary search the last cost added
    lo=0
    hi=a*int((n**0.5)*3+3)

    while 1:
        mid=(lo+hi)//2
        mid=11
        # count stuff
        c0=0    # < mid
        c1=0    # = mid
        for i in range(mid//a+1):
            j=(mid-i*a)//b
            if (mid-i*a)%b!=0:
                # c0 += iC0 + (i+1)C1 + (i+2)C2 + ... + (i+j)Cj
                for k in range(j+1):
                    print(mid,i,k)
                    c0+=getcom(i,k)
                    if c0>n: break
            else:
                for k in range(j):
                    print(mid,i,k)
                    c0+=getcom(i,k)
                    if c0>n: break
                print(mid,i,j,"c1")
                c1+=getcom(i,j)
        print(mid,"is",c0,c1)
        if n<c0:
            hi=mid-1
        elif c0+c1<n:
            lo=mid+1
        else:
            # mid is correct cutoff
            lowcost=0   # sum of all cost, where cost < mid
            for i in range(mid//a+1):
                j=(mid-i*a)//b
                if (mid-i*a)%b!=0:
                    for k in range(j+1):
                        lowcost+=getcom(i,k)*(i*a+k*b)
                else:
                    for k in range(j):
                        lowcost+=getcom(i,k)*(i*a+k*b)
            temp=lowcost+(n-c0)*mid
            print(temp+n*(a+b))
            break


t = input()

t = t.split()

n = int(t[0])

c1 = int(t[1])

c2 = int(t[2])

t = input()

d = 0

for i in t:

    if(i=="1"):

        d = d+1

min = 10**1488

for i in range(1, d+1):

    t = c1*i + i*c2*(((n//i)-1)**2) + c2*(n%i)*(2*(n//i)-1)

    if t<min:

        min = t

print(min)

# Made By Mostafa_Khaled


n, c1, c2 = [int(x) for x in input().split(' ')]
s = input()

cnt = s.count('1')

def price(x):
    return c1 + c2 * (x - 1) ** 2

prices = []

for i in range(1, cnt + 1):
    bigGroupsPeople = n // i + 1
    numBigGroups = n % i
    smallGroupsPeople = n // i
    numSmallGroups = i - n % i
    totalPrice = numBigGroups * price(bigGroupsPeople) + numSmallGroups * price(smallGroupsPeople)
    prices.append(totalPrice)

print(min(prices))


n, m = map(int, raw_input().split())
m += 1

def calc(l, r, eq, eq_i):
	if l > r: return 1
	key = l, eq, eq_i
	if key in f: return f[key]

	t = 0
	for x in (['0', '1'] if s[l] == '?' else [s[l]]):
		if l == r: a = [x]
		else: a = ['0', '1'] if s[r] == '?' else [s[r]]
		for y in a:
			if not((eq and x > y) or (eq_i and x == y == '1')): t += calc(l + 1, r - 1, eq and x == y, eq_i and x != y)
	f[key] = t
	return t

s = ['?'] * n
for i in xrange(n):
	s[i] = '0'
	f = {}
	p = calc(0, n - 1, True, True)
	if m > p:
		m -= p
		s[i] = '1'

print ''.join(s) if s[0] == '0' else -1


from itertools import *

def foo(i, rev, inv):
    j = n - 1 - i
    if i > j: return 1
    if (i, rev, inv) in cache: return cache[i, rev, inv]
    ret = 0
    for a, b in product((0, 1), repeat = 2):
        if (i < j or a == b) and s[i] in (None, a) and s[j] in (None, b) and (a <= b or rev) and (a <= (b ^ 1) or inv):
            ret += foo(i + 1, rev or a < b, inv or a < (b ^ 1))
    cache[i, rev, inv] = ret
    return ret

n, k = map(int, raw_input().split())
k += 1
s = [None] * n
for i in xrange(n):
    cache = {}
    s[i] = 0
    t = foo(0, False, False)
    if k > t:
        k -= t
        s[i] = 1
print ''.join(map(str, s)) if s[0] == 0 else -1


n, m = map(int, input().split())
m += 1

def calc(l, r, eq, eq_i):
    if l > r:
        return 1
    key = l, eq, eq_i
    if key in f:
        return f[key]

    t = 0
    for x in (['0', '1'] if s[l] == '?' else [s[l]]):
        if l == r:
            a = [x]
        else:
            a = ['0', '1'] if s[r] == '?' else [s[r]]
        for y in a:
            if not((eq and x > y) or (eq_i and x == y == '1')):
                t += calc(l + 1, r - 1, eq and x == y, eq_i and x != y)
    f[key] = t
    return t

s = ['?'] * n
for i in range(n):
    s[i] = '0'
    f = {}
    p = calc(0, n - 1, True, True)
    if m > p:
        m -= p
        s[i] = '1'

if s[0] == '0':
    print(''.join(s))
else:
    print(-1)


def raschot(d, e, g, h):
    if d > e:
        return 1
    key = d, g, h
    if key in b:
        return b[key]
    f = 0
    for x in (['0', '1'] if a0[d] == '?' else [a0[d]]):
        if d == e:
            a = [x]
        else:
            a = ['0', '1'] if a0[e] == '?' else [a0[e]]
        for y in a:
            if not ((g and x > y) or (h and x == y == '1')):
                f += raschot(d + 1, e - 1, g and x == y, h and x != y)
    b[key] = f
    return f

n, m = map(int, input().split())
m += 1
a0 = ['?'] * n
for i in range(n):
    a0[i] = '0'
    b = {}
    c = raschot(0, n - 1, True, True)
    if m > c:
        m -= c
        a0[i] = '1'
if a0[0] == '0':
    print(''.join(a0))
else:
    print(-1)


from itertools import *

def foo(i, rev, inv):
    j = n - 1 - i
    if i >= j: return 1
    if (i, rev, inv) in cache: return cache[i, rev, inv]
    ret = 0
    for a, b in product((0, 1), repeat = 2):
        if s[i] in (None, a) and s[j] in (None, b) and (a <= b or rev) and (a <= (b ^ 1) or inv):
            ret += foo(i + 1, rev or a < b, inv or a < (b ^ 1))
    cache[i, rev, inv] = ret
    return ret

n, k = map(int, raw_input().split())
k += 1
s = [None] * n
for i in xrange(n):
    cache = {}
    s[i] = 0
    t = foo(0, False, False)
    if k > t:
        k -= t
        s[i] = 1
print ''.join(map(str, s)) if s[0] == 0 else -1


def print4(x):
    return '%s%s%s%s' % ( x/1000, (x/100)%10, (x/10)%10, x%10)

def printall(n,m,v):
    count = 0
    for i in range(10000):
        for j in v[(abs(n-i), 4)]:
            if count == m:
                return
            print '%s%s' % (print4(i), print4(j))
            count += 1

v = {}
e = {}
for i in range(10000):
    for j in range(1,5):
        e[(i,j)] = set()
        v[(i,j)] = set()

for i in range(10):
    e[(i,1)].add(i)
    v[(i,1)].add(i)

for i in range(0,100):
    e[(i,2)].add(i)
    v[(i,2)].add(i)
    d, u = i/10, i%10
    pos = [d+u, abs(d-u), d*u]
    for j in pos:
        e[(i, 2)].add(j)
        v[(j,2)].add(i)

for i in range(0,1000):
    e[(i,3)].add(i)
    v[(i,3)].add(i)
    cuts = []
    cuts.append(( (i/100, 1), (i%100, 2) ))
    cuts.append(( (i/10, 2), (i%10, 1) ))
    for one, two in cuts:
        pos = []
        for x in e[one]:
            for y in e[two]:
                pos.append(x+y)
                pos.append(x*y)
                pos.append(abs(x-y))
        pos = set(pos)
        for j in pos:
            e[(i, 3)].add(j)
            v[(j, 3)].add(i)

for i in range(0,10000):
    e[(i,4)].add(i)
    v[(i,4)].add(i)
    cuts = []
    cuts.append(( (i/1000, 1), (i%1000, 3) ))
    cuts.append(( (i/100, 2), (i%100, 2) ))
    cuts.append(( (i/10, 3), (i%10, 1) ))
    for one, two in cuts:
        pos = []
        for x in e[one]:
            for y in e[two]:
                pos.append(x+y)
                pos.append(x*y)
                pos.append(abs(x-y))
        pos = set(pos)
        for j in pos:
            e[(i, 4)].add(j)
            v[(j, 4)].add(i)

n, m = map(int, raw_input().split())
printall(n,m,v)


N,M = map(int,raw_input().split())

P = {}
Q = {}
for i in range(10001):
    for j in range(1,5):
        P[(i,j)] = set()
        Q[(i,j)] = set()

for i in range(10):
    P[(i,1)].add(i)
    Q[(i,1)].add(i)
for i in range(100):
    P[(i,2)].add(i)
    Q[(i,2)].add(i)
    a,b = i/10,i%10
    next = [a+b,abs(a-b),a*b]
    for j in next:
        P[(j,2)].add(i)
        Q[(i,2)].add(j)
for i in range(1000):
    P[(i,3)].add(i)
    Q[(i,3)].add(i)
    candidate = [((i/100,1),(i%100,2)),((i/10,2),(i%10,1))]
    next = []
    for p,q in candidate:
        for a in Q[p]:
            for b in Q[q]:
                next.append(a+b)
                next.append(abs(a-b))
                next.append(a*b)
    next = set(next)
    for j in next:
        P[(j,3)].add(i)
        Q[(i,3)].add(j)
for i in range(10000):
    P[(i,4)].add(i)
    Q[(i,4)].add(i)
    candidate = [((i/1000,1),(i%1000,3)),((i/100,2),(i%100,2)),((i/10,3),(i%10,1))]
    next = []
    for p,q in candidate:
        for a in Q[p]:
            for b in Q[q]:
                next.append(a+b)
                next.append(abs(a-b))
                next.append(a*b)
    next = set(next)
    for j in next:
        P[(j,4)].add(i)
        Q[(i,4)].add(j)

def f(n,m,p):
    for i in range(10000):
        for j in p[(abs(n-i),4)]:
            print '%04d%04d'%(i,j)
            m -= 1
            if m == 0:
                return

f(N,M,P)


#!/usr/bin/python
import sys

a = []

def gen (n, d):
	global a
	if n > 0:
		a += [n]
	if d > 0:
		gen (n * 10 + 4, d - 1)
		gen (n * 10 + 7, d - 1)

def go (l, r, pos, c):
	l = max (l, pos)
	r = min (r, c)
#	print l, r, c
	return max (r - l + 1, 0) * c

def fact (n):
	if n > 12:
		return 10 ** 9 + 1
	if n == 0:
		return 1
	return n * fact (n - 1)

gen (0, 9)
a.sort ()

while True:
	s = sys.stdin.readline ().strip ()
	if s == '':
		s = sys.stdin.readline ().strip ()
		if s == '':
			break
	n, k = [int (x) for x in s.split ()]
	if n <= 12:
		if k > fact (n):
			print -1
			continue
	m = max (n - 13, 0)
	d = n - m
	res = 0
	for c in a:
		if c <= m:
			res = res + 1
	b = range (n - d + 1, n + 1)
	p = range (n - d + 1, n + 1)
	q = []
	k -= 1
	for i in range (d)[::-1]:
		j = k / fact (i)
#		print k, fact (i), j
		k %= fact (i)
		q += [b[j]]
		b = b[:j] + b[j + 1:]
#		print p, q, b
	for i in range (d):
		if p[i] in a and q[i] in a:
			res += 1
	print res


import math
def isLucky(num):
	s = str(num)
	for i in s:
		if i != '4' and i != '7':
			return False
	return True

def getLucky(d):
	if d == 1:
		for i in [4, 7]:
			yield str(i)
	else:
		l = [i for i in getLucky(d-1)]
		for j in l:
			yield '4'+j
		for j in l:
			yield '7'+j

luckies = []
for d in range(1,11):
	for i in getLucky(d):
		luckies.append(int(i))

def canto(l, k):
	# find the k(th) permutation of list l, k counts from 1
	n = len(l)
	p = k - 1
	a = []
	i = n - 1
	mark = [False]*(n+1)
	while len(a) < n:
		fac = math.factorial(i)

		a.append(p/fac)
		p %= fac
		i -= 1
		j = 1
		cnt = 0
		while cnt < a[-1]+1:
			if not mark[j]:
				cnt += 1
			j += 1
		a[-1] = j-1
		mark[a[-1]] = True
	return [l[i-1] for i in a]

n, k = map(int, raw_input().split())
if n < 20 and k > math.factorial(n):
	print -1
else:
	for tail in xrange(1, 31):
		fac = math.factorial(tail)
		if fac >= k:
			break
	l = [i for i in xrange(n+1-tail, n+1)]
	p_tail = canto(l, k)
	# print 'tail',tail
	# print p_tail

	ans = 0
	for lucky in luckies:
		if lucky > n: break
		# print 'lucky is',lucky
		if lucky <= n-tail:
			ans += 1
			# print lucky
		else:
			i = p_tail.index(lucky)
			if isLucky(n-tail+1+i):
				ans += 1
				# print lucky
	print ans