def main():
    from sys import stdin, setrecursionlimit
    # setrecursionlimit(1000000)
    input = stdin.readline
    def iinput(): return int(input())
    def sinput(): return input().rstrip()
    def i0input(): return int(input()) - 1
    def linput(): return list(input().split())
    def liinput(): return list(map(int, input().split()))
    def miinput(): return map(int, input().split())
    def li0input(): return list(map(lambda x: int(x) - 1, input().split()))
    def mi0input(): return map(lambda x: int(x) - 1, input().split())
    INF = 1000000000000000000
    MOD = 1000000007

    '''
    c を固定
    a + b = N - c = K は gcd(a, b) で割り切れる -> K の約数のうち K 以外をひとつ k と固定
    k + k + ... + k = K
    l = K / k
    このとき、分け方は phi(l)
    '''

    def make_divisors(n):
        lower_divisors , upper_divisors = [], []
        i = 1
        while i*i <= n:
            if n % i == 0:
                lower_divisors.append(i)
                if i != n // i:
                    upper_divisors.append(n//i)
            i += 1
        return lower_divisors + upper_divisors[::-1]

    class Totient:
        def __init__(self, N:int) -> None:
            self.N = N
            self.enum_tortient = [i for i in range(N+1)]
            self.is_prime = [True] * (N + 1)
            self.is_prime[0] = False
            self.is_prime[1] = False
            for p in range(2, N+1):
                if self.is_prime[p]:
                    self.enum_tortient[p] = p - 1
                    for n in range(2*p, N+1, p):
                        self.is_prime[n] = False
                        self.enum_tortient[n] = self.enum_tortient[n] // p * (p - 1)
        def phi(self, K:int) -> int:
            assert(K <= self.N)
            return self.enum_tortient[K]

    N = iinput()
    ans = 0
    from math import gcd

    tot = Totient(N)
    for c in range(1, N-1):
        K = N - c
        for g in make_divisors(K)[:-1]:
            ans += c * tot.phi(K//g) * g // gcd(g, c)
    print(ans)

main()


def gets():
    return list(map(int, raw_input().split()))
n, m, d = gets()
a = [ tuple(gets()) for i in range(n) ]
b = [ tuple(gets()) for i in range(m) ]
def mycmp(lef, rig):
    if lef[0] == rig[0]:
        return lef[1] - rig[1]
    return rig[0]-lef[0]
a.sort(cmp = mycmp)
b.sort(cmp = mycmp)
ans = 0
cur = 0
wid = 0
j = n
for i in range(n):
    cur += a[i][0]
    wid += a[i][1]
for i in range(m):
    cur += b[i][0]
    wid += b[i][1]
    while wid > d :
        j -= 1
        if j <= 0:
            break
        cur -= a[j][0]
        wid -= a[j][1]
    if j <= 0:
        break
    ans = max(ans, cur)
print ans


from sys import stdin, exit
from random import randint

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

active = [i + 1 for i in range(n)]

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    best = (-1, -1)
    bsz = 10 ** 6
    for it in xrange(30):
        idx1 = randint(0, n - 1)
        idx2 = randint(0, n - 1)
        if idx1 == idx2:
            continue

        i = active[idx1]
        j = active[idx2]

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        #answer.append((i, j))
        #K -= 1

        n_act = []
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        n_act.append(k)

        #active = n_act
        good = True
        if len(n_act) < bsz:
            bsz = len(n_act)
            best = (i, j)

    if not good:
        no_solution()

    i, j = best

    if a[i] * b[j] == a[j] * b[i]:
        continue

    x_high = c[j] * b[i] - c[i] * b[j]
    y_high = a[j] * c[i] - a[i] * c[j]

    low = a[i] * b[j] - a[j] * b[i]

    answer.append((i, j))
    K -= 1

    n_act = []
    for k in active:
        if k == i or k == j:
            continue

        low_prime = a[k] * b[j] - a[j] * b[k]
        if low_prime == 0:
            n_act.append(k)
            continue

        x_high_prime = c[j] * b[k] - c[k] * b[j]
        y_high_prime = a[j] * c[k] - a[k] * c[j]

        if x_high * low_prime != x_high_prime * low or \
                y_high * low_prime != y_high_prime * low:
                    n_act.append(k)
    active = n_act

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()


mod, sx, sy, dx, dy, t = map(int, raw_input().split())
v = (sx - 1, sy - 1, dx + sx + sy, dy + sx + sy, 1, 1)
A = [
[1, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[1, 1, 2, 1, 1, 2],
[1, 1, 1, 2, 1, 2],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1]
]
I = lambda: [[1 if i == j else 0 for j in xrange(6)] for i in xrange(6)]
def mul(M, N):
    global mod
    res = [[0] * 6 for i in xrange(6)]
    for i in xrange(6):
        for j in xrange(6):
            for k in xrange(6):
                res[i][j] += M[i][k] * N[k][j]
                res[i][j] %= mod
    return res
def power(M, k):
    if k > 1:
        res = power(M, k/2)
        res = mul(res, res)
        if k % 2:
            res = mul(res, M)
        return res
    elif k == 1:
        return M
    else:
        return I()
B = power(A, t)
V = [0] * 6
for i in xrange(6):
    for j in xrange(6):
        V[i] += B[i][j] * v[j]
        V[i] %= mod
print V[0] + 1, V[1] + 1


m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0

def add(b, k):
    k = t[k]
    while k:
        e = es[k]
        if b[-1] > e: b[-1] = e
        b[e] += 1
        k = ns[k]

def delete(b):
   for i in range(b[m - 1], m + 1):
       if b[i]:
           b[i] -= 1
           b[-1] = i
           return i

def calc(k):
    global b
    q = 0
    b = [0] * m
    b[-1] = m
    take = rank - dn
    if take < 0: take = 0
    add(b, k)
    add(b, k - 1)
    for i in range(1, take + 1): q += delete(b)
    for i in range(k - 1): add(b, i)
    for i in range(k + 1, P + 1): add(b, i)
    for i in range(1, k - take + 1): q += delete(b)
    return q

n, k = map(int, input().split())
rank = n - k + 1

if rank == 0:
    print('0')
    exit(0)

for i in range(1, n + 1):
    p, e = map(int, input().split())
    if p > P: P = p
    c[p] += 1
    es[i], ns[i] = e, t[p]
    t[p] = i

dn = 0
for i in range(1, n + 1):
    if i > 1: dn += c[i - 2]
    if c[i] + c[i - 1] + dn >= rank and rank <= i + dn:
        u = calc(i)
        if i < n:
            dn += c[i - 1]
            v = calc(i + 1)
            if u > v: u = v
        if i < n - 1:
            dn += c[i]
            v = calc(i + 2)
            if u > v: u = v
        print(u)
        exit(0)

print('-1')


n=int(input())*2
s=input()
d=dict()
aux=''
for i in range(len(s)):
    if s[i]=='(':
        d.update({(i,1):i+1})
        x=aux+')'
        for j in range(1,i+2):
            print(x[j::],s[0:len(x)-j],len(x),j)
            if x[j::] ==s[0:len(x)-j]:
                d.update({(len(aux),0):len(x[j::])})
                break
    else:
        d.update({(i,0):i+1})
        x=aux+'('
        for j in range(1,i+2):
            if x[j::]  ==s[0:len(x)-j]:
                d.update({(len(aux),1):len(x[j::])})
                break
    aux+=s[i]
d.update({(len(s),1):len(s)})
d.update({(len(s),0):len(s)})
dp=[[[0 for i in range(len(s)+1)] for j in range(n//2+1)] for k in range(n+1)]
dp[0][0][0]=1
mod=10**9+7
for i in range(n):
    for j in range(1,(n//2)+1):
        for k in range(len(s)+1):
            dp[i+1][j-1][d[(k,0)]]=(dp[i][j][k]+dp[i+1][j-1][d[(k,0)]])%mod
    for j in range(n//2):
        for k in range(len(s)+1):
            dp[i+1][j+1][d[(k,1)]]=(dp[i][j][k]+dp[i+1][j+1][d[(k,1)]])%mod
print(dp[n][0][len(s)]%mod)


import sys
def mulMatrix(a, b, p):
	n = len(a)
	c = []
	for i in range(n):
		c.append([0] * n)
	for i in range(n):
		for j in range(n):
			for k in range(n):
				c[i][j] += a[i][k] * b[k][j]
				c[i][j] %= p
	return c

def powMatrix(a, pw, p):
	n = len(a)
	r = []
	for i in range(n):
		l = [0] * n
		l[i] = 1
		r.append(l)
	while pw:
		if pw & 1:
			r = mulMatrix(r, a, p)
		a = mulMatrix(a, a, p)
		pw >>= 1
	return r

def getFib(n, p):
	if n < 0: return 0
	if n < 2: return 1
	r = powMatrix([[1, 1], [1, 0]], n - 1, p)
	return (r[0][0] + r[0][1]) % p

def getSumPow3(x, p):
	if x == 0:
		return 0
	if x == 1:
		return 1
	if x & 1:
		t = getSumPow3(x - 1, p)
		return (t * 3 + 1) % p
	else:
		t = getSumPow3(x >> 1, p)
		return (t + t * pow(3, x >> 1, p)) % p

def mod(x, p):
	x %= p
	if x < 0:
		x += p
	return x

def getSum(first, last, mid, n, p):
	(first, last, mid) = (mod(first, p), mod(last, p), mod(mid, p))
	#print first, last, mid
	return ((first + last) * (getSumPow3(n, p) + 1) + mid * pow(3, n, p)) % p

def main():
	(n, x, y, p) = sys.stdin.readline().split(' ')
	(n, x, y, p) = (long(n), long(x), long(y), long(p))
	a = sys.stdin.readline().strip().split(' ')
	s = 0
	for i in xrange(n):
		a[i] = long(a[i])
		a[i] %= p
		s += a[i]

	if n == 1:
		print a[0]
		return

	s = getSum(a[0], a[-1], s - a[0] - a[-1], x, p)

	last = (a[-1] * getFib(x, p) + a[-2] * getFib(x - 1, p)) % p

	s = getSum(a[0], last, s - a[0] - last, y, p)
	print s

	#3 ** (s - a[0] - a[-1])
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):
    	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
input = sys.stdin.readline

from functools import lru_cache

k, M = map(int, input().split())

MOD = M

def modmul(x, y, c = 0):
    return (x * y + c) % MOD

mod_mul = modmul

def inv(x):
    return pow(x, MOD - 2, MOD)

MAX = 10 ** 5

fact = [1]
for i in range(1, MAX):
    fact.append(modmul(i, fact[i-1]))

invfact = [1] * (MAX)
invfact[MAX - 1] = inv(fact[MAX - 1])
for i in range(MAX - 2, -1, -1):
    invfact[i] = modmul(i + 1, invfact[i+1])

def comb(x, y):
    assert 0 <= y <= x

    return modmul(fact[x], modmul(invfact[y], invfact[x - y]))

def invcomb(x, y):
    return modmul(invfact[x], modmul(fact[y], fact[x - y]))

def invs(x):
    return modmul(fact[x - 1], invfact[x])

def count(a, b):
    if a + b == 0:
        return 1
    return modmul(a, fact[a + b - 1])

n = k

pn1 = [1]
for i in range(5000):
    pn1.append(modmul(pn1[-1], n - 1))

out = 0
for i in range(1, n):

    pni = [1]
    for _ in range(5000):
        pni.append(modmul(pni[-1], n - i))

    for j in range(i + 1):
        if n - i - j < 0:
            continue

        stab = comb(n, i)
        app = modmul(comb(i, j), comb(n - i, n - i - j))
        order = count(j, n - i - j)
        sao = modmul(modmul(stab, app), order)
        #sao = 1

        #u1 = pow(n - i, i - j, M)
        #u2 = pow(n - 1, j, M)
        u1 = pni[i - j]
        u2 = pn1[j]
        u = modmul(u1, u2)
        #u = 1

        #print(i, j, stab, app, order, u1, u2)

        out += modmul(sao, u)

print(out % M)


from collections import Counter
n = int(input())
a = list(map(int, input().split()))

def get(cnt):
    c = Counter(a)
    last = []
    while c[1] and (cnt is None or len(last) < cnt):
        x = 1
        while c[x]:
            c[x] -= 1
            x *= 2
        last.append(x >> 1)
    rem = sorted(c.elements())
    i = 0
    for x in last[::-1]:
        if i < len(rem) and rem[i] < 2 * x:
            i += 1
    return len(last) if i == len(rem) else 0

mx = get(None)
lo, hi = 0, mx
while lo < hi:
    mid = (lo + hi) >> 1
    if get(mid):
        hi = mid
    else:
        lo = mid + 1
if mx:
    print(*range(lo, mx + 1))
else:
    print(-1)


import sys
from math import lcm
from collections import defaultdict

def solve(p):
	poly = int(p[::-1], 2)
	assert p[0] == '1' and p[-1] == '1'
	degree = len(p) - 1
	def reduce(a):
		while a.bit_length() > degree:
			b = a.bit_length() - degree - 1
			a ^= poly << b
		assert a < (1 << degree)
		return a

	def mul(a, b):
		a = reduce(a)
		b = reduce(b)
		val = 0
		for i in range(degree):
			if (a >> i) & 1:
				val ^= (b << i)
		for i in range(degree, -1, -1):
			if (val >> (degree + i)) & 1:
				val ^= poly << i
		return val

	def pow(a, k):
		res = 1
		while k:
			if k & 1:
				res = mul(res, a)
			k >>= 1
			a = mul(a, a)
		return res

	pfs = defaultdict(int)
	pfs[2] += degree
	for i in range(1, degree + 1):
		cur = 2 ** i - 1
		p = 2
		while p * p <= cur:
			while cur % p == 0:
				cur //= p
				pfs[p] += 1
			p += 1
		if cur > 1:
			pfs[cur] += 1
	order_multiple = 1
	for p in pfs:
		order_multiple *= p ** pfs[p]

	order = order_multiple
	x = reduce(1 << 1)
	for p in pfs:
		while order % p == 0 and pow(x, order // p) == 1:
			order //= p
	return order

s = input()
if '1' not in s:
	print(-1)
	sys.exit()

p = s.lstrip('0')
l0 = len(s) - len(p)
p = p.rstrip('0')

res = solve(p)
print(f"{1 + l0} {1 + l0 + res}")


def main():
    l = [input()[4:] for _ in range(int(input()))]
    for i, s in enumerate(l):
        le = len(s)
        if le == 1:
            s = ("199", "198")[s == "9"] + s
        elif le == 2:
            s = "1999" if s == "99" else "20" + s
        elif le == 3:
            s = "2" + s
        else:
            if s != "9" * le:
                s = "1" + s
        l[i] = s
    print('\n'.join(l))

if __name__ == '__main__':
    main()


# coding: utf-8

import math, sys, time, bisect, sys

k = int(raw_input())
n = int(raw_input())
pts = []
for _ in xrange(n*k):
	x,y = map(int, raw_input().split())
	pts.append( (x,y) )

def distribution(x,y,pts=pts,n=n,k=k):
	# smallest circle: radius 2.5e5, extended to at most 1.1 times that. but we can also be about 1e5 off on the radius.
	# so all points will be within 2.5*0.9-1=1.25 up to 1+2.5*1.1=3.75
	rs = []
	for x2,y2 in pts:
		rs.append(((((x-x2)**2+(y-y2)**2)**.5), math.atan2(y2-y, x2-x)))
	rs.sort()

	angle_cumbuckets = [[0] for _ in xrange(12)]
	angles = [-math.pi+i*2*math.pi/len(angle_cumbuckets) for i in xrange(len(angle_cumbuckets)+1)]
	for i in xrange(len(angle_cumbuckets)):
		angle1, angle2 = angles[i], angles[i+1]
		for r,a in rs:
			if angle1<=a<angle2:
				angle_cumbuckets[i].append( angle_cumbuckets[i][-1] + 1)
			else:
				angle_cumbuckets[i].append( angle_cumbuckets[i][-1] )

	best = (1e12,None)
	uniformity = None
	for i in xrange(len(rs)):
		r1 = rs[i][0]
		# points between radii r*0.9-OFFSET to r*1.1+OFFSET when radius is r

		r = (r1+OFFSET*1e5/2.)/0.9 # r is this without OFFSET but let's average it (this is not the correct avg)
		if (r1+OFFSET*1e5)/0.9<2.5e5:
			continue
		r2 = (r1+OFFSET*1e5)/0.9*1.1+OFFSET*1e5

		j = bisect.bisect(rs, (r2,))
		if j-i < n*0.99:
			continue

		j = min(j, len(rs)-1)
		dist = j-i
		possible_r = r
		candidate = (-dist, possible_r)
		if candidate<best and all([angle_cumbuckets[a][j+1]-angle_cumbuckets[a][i+1]>=0.1*n/len(angle_cumbuckets) for a in xrange(len(angle_cumbuckets))]):
			best=candidate
			uniformity = min([angle_cumbuckets[a][j+1]-angle_cumbuckets[a][i+1] for a in xrange(len(angle_cumbuckets))])#/(float(n)/len(angle_cumbuckets))
		if j == len(rs)-1:
			break
	best = list(best)
	best[0] = -uniformity if uniformity is not None else None
	return tuple(best)

def J(data):
	ret = 0.0
	for x2,y2 in pts:
		thing = 1e15
		for i in xrange(k):
			x,y,r = data[3*i], data[3*i+1], data[3*i+2]
			#ret += abs(((x-x2)**2+(y-y2)**2)/r-1)
			thing = min(thing, math.sqrt(abs(r**2-((x-x2)**2+(y-y2)**2))))
		ret += thing
	return ret

def gradient_descent_auto(x,J,delta, alpha=1000):
	iterations = 200
	rolling = []
	for it in xrange(iterations):
		j = J(x)
		if len(rolling)<4:
			rolling.append((j,x[:]))
		else:
			if all(0.999<r[0]/j<1.001 for r in rolling[-4:]):
				return x, it
			if rolling[-4][0] < j:
				alpha /= 3.1622
				j,x = min(rolling)
				rolling = []
			else:
				rolling.append((j,x[:]))
		dx = []
		for i in xrange(len(x)):
			x2 = x[:]
			x2[i] += delta
			dx.append((J(x2)-j)/delta)

		for i in xrange(len(x)):
			x[i] -= dx[i]*alpha
			if i%3 == 2: # radius
				if x[i] < 0:
					x[i] = -x[i]
				x[i] = max(230000,x[i])
				x[i] = min(800000,x[i])
			else:
				x[i] = min(x[i], 1e6)
				x[i] = max(x[i], -1e6)
	return x, it

SIZE = 34
RANGE = 1.25e6
OFFSET = 2*RANGE/(SIZE-1.0)/1e5*5/8.
#print OFFSET

count = 0
peaks = []
for i in xrange(SIZE):
	for j in xrange(SIZE):
		x = -RANGE + (i+(0.5 if j%2==0 else 0))/(SIZE-1.)*2*RANGE
		y = -RANGE + j/(SIZE-1.)*2*RANGE
		count += 1
		if (x**2+y**2)**.5>RANGE:
			continue
		dist = distribution(x,y)
		if dist[1] is not None:
			peaks.append( (dist, (x,y)))
peaks.sort()

def go(candidates, pts, k, result=None):
	if result is None:
		result = []
	for i,((uniformity,r),(x,y)) in enumerate(candidates):
		remove_these = [(x2,y2) for (x2,y2) in pts if r*0.8-OFFSET*1e5 <= ((x-x2)**2+(y-y2)**2)**.5 <= r*1.2+OFFSET*1e5]
		new_pts = list(set(pts)-set(remove_these))
		if k == 1:
			if len(new_pts) == 0:
				return result+[(x,y,r)]
		else:
			ret = go(candidates[i+1:], new_pts, k-1, result+[(x,y,r)])
			if ret is not False:
				return ret
	return False

yay = go(peaks, pts, k)

if yay is False:
	print 'no answer'
	sys.exit(0)

data = []
for (x,y,r) in yay:
	data += [x,y,r]
data, its = gradient_descent_auto(data, J, 1.0, 10)
may = []
for i in range(k):
	may.append((data[i*3+0], data[i*3+1], data[i*3+2]))

for (x,y,r) in may:
	print x, y, r


import math
n, t = map(int, raw_input().split())

for i in range(55):
    comb = [[0]*55 for _ in range(55)]
for i in range(55):
    for j in range(i+1):
        if (i == 0 or j == 0): comb[i][j] = 1
        else:
            comb[i][j] = comb[i-1][j] + comb[i-1][j-1]

def gao(m, k):
    ret = 0
    while m > 0:
        p = int(math.log(m, 2))
        ret += comb[p][k]
        k -= 1
        m -= 2**p
        if m == 0:
            if k == 0:
                ret += 1
            break
        if k < 0:
            break
    return ret

tmp = 0
num = t
while (num > 0):
    if (num % 2 == 1):
        tmp += 1
    num /= 2
    if (tmp > 1):
        break
if (tmp > 1):
    print 0
else:
    k = int(math.log(t, 2))
    ans = gao(n+1, k+1)
    if t == 1:
        ans -= 1
    print ans


from fractions import Fraction

hash = [0 for i in xrange(10001)]

def solve(n):
    if not isinstance(hash[n], int):
        return hash[n]
    m, cnt = n, 0
    while m > 1:
        if m & 1:
            break
        m >>= 1
        cnt += 1
    else:
        hash[n] = Fraction(cnt)
        return Fraction(cnt)

    l, step = [[1, 0]], 0
    while l[0][0] < n:
        l[0][0] <<= 1
        l[0][1] += 1
    l[0][0] -= n
    while True:
        l.append([l[-1][0], 0])
        while l[-1][0] < n:
            l[-1][0] <<= 1
            l[-1][1] += 1
        l[-1][0] -= n
        step += l[-1][1]
        if l[-1][0] == l[0][0]:
            l.pop()
            break

    part1 = part2 = Fraction()
    p = Fraction((1 << step))
    sum = 0
    for part in l:
        p *= Fraction(1, 1 << part[1])
        sum += part[1]
        part1 += p * sum
        part2 += p * step

    t = Fraction(1, (1 << step) - 1)
    ret = t * (part1 + part2 * t) * n

    for i in xrange(2, n / 2):
        if n % i == 0:
            t = solve(i) + solve(n / i)
            if t < ret: ret = t

    hash[n] = ret
    return ret

n = int(raw_input())
ans = str(solve(n))
if ans.find('/') == -1:
    ans += '/1'
print ans


rr=raw_input
rrI = lambda: int(rr())
rrM = lambda: map(int,rr().split())
debug=0
if debug:
    fi = open('t.txt','r')
    rr=lambda: fi.readline().replace('\n','')

def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
#N = 75
#from time import time
#S  = '100000111111101000100001011100010111110011111011100011001111101111100011110'
#tt = time()
#print tt

MOD = 10**9 + 7
UPPER = 22

number = [ [0]*(N+1) for _ in xrange(N) ]
for i in xrange(N):
    for j in xrange(i+1, N+1):
        number[i][j] = min(22, int(S[i:j],2))

memo = [ [None]*(1<<UPPER) for _ in xrange(N+1)]
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    fetch = memo[i][mask]
    if fetch is not None:
        return fetch
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, N+1):
        num = number[i][j]
        if num == 0: continue
        if num >= UPPER: break
        ans += dp(j, mask | (1<<(num-1)))
        if ans >= MOD:
            ans %= MOD
    memo[i][mask] = ans
    return ans

fans = i = 0
while i < N:
    fans += dp(i, 0)
    fans %= MOD
    i += 1
print fans
#print time()-tt

"""
def good_mask(x):
    if x == 0: return False
    return (x+1) & x == 0

N = rrI()
S = rr()
##print '.'
#N = 75
#import random
#S = "".join(str(random.randint(0,1)) for _ in xrange(N))
MOD = 10**9 + 7
UPPER = 22

memoslide = {N : 0, N-1:0}
def slide(j):
    if j in memoslide:
        return memoslide[j]
    if S[j] == '1':
        memoslide[j] = 0
        return 0
    else:
        k = j
        while k < len(S) and S[k] == '0':
            k += 1
        memoslide[j] = k - j
        return k - j

memo = {}
def dp(i, mask):
    #Having made a cut already before position i,
    #and having a set of mask taken
    #how many ways?
    if i == N:
        return 1 if good_mask(mask) else 0
    if (i,mask) in memo:
        return memo[i,mask]
    ans = 1 if good_mask(mask) else 0
    for j in xrange(i+1, N+1):
        num = int(S[i:j], 2)
        if num == 0: continue
        if num >= UPPER: break
        if num > 8:
            #prune
            newmask = mask
            ii = excess = 0
            while newmask:
                if newmask%2 == 0:
                    excess += len(bin(ii)) - 2
                ii += 1
                newmask /= 2
            if excess > N-j+1:
                break
        k = slide(j)
        newmask = mask | (1<<(num-1))
        bns = dp(j + k, newmask)
        for kk in xrange(k):
            memo[(j + kk, newmask)] = bns
        ans += (1+k) * bns

        if ans >= MOD:
            ans %= MOD
    memo[i, mask] = ans
    return ans

fans = 0
for i in xrange(N):
    fans += dp(i, 0)
    if fans >= MOD:
        fans %= MOD
print fans
"""


import sys

d0 = [0,0,0,0,1,-1,0,1,-1,0,0]

def clucky(x):
    cnt = 0
    while x!=0:
        if x%10 in [4,7]: cnt+=1
        x/=10
    return cnt

def solve1(a,add):
    des = clucky(a)+add
    assert des>=0
    b = a+1
    step = 1
    nfree = 0
    while 1:
        while b%(step*10)==0:
            step*=10
            nfree+=1

        tmp = clucky(b/step)
        if tmp+nfree>=des and tmp<=des:
            res = int(str(b/step)+"".join(['0']*(nfree-(des-tmp)))+''.join(['4']*(des-tmp)))
            return res
        b+=step
    assert False

def solve(a,l):
    #print "calling",a,l
    if l==1:
        return solve1(a,0)

    #with large l, b and a has the same last digit
    res = solve(a/10,(a+l-1)/10-a/10+1)*10+a%10
    if l>=30: return res

    #otherwise, there might be more than 1 match:
    for b in range(10):
        if b==a%10: continue
        cur = clucky(a)
        match = True
        pos10 = []
        for i in range(1,min(l,20)):
            next = clucky(a+i)
            if (b+i)%10==0: pos10.append(next-cur)
            elif next-cur!=d0[(b+i)%10]:
                match = False
                break
            cur = next
        if match:
            assert len(pos10)<=1
            if len(pos10)==0:
                if b>a%10:
                    res = min(res,a-a%10+b)
                else:
                    res = min(res,solve(a/10,(a+l-1)/10-a/10+1)*10+b)
            else:
                delta = pos10[0]
                for b2 in range(9): #omiting b2=9
                    if d0[b2+1]!=delta: continue
                    bb = b2*10+b
                    if bb>a%100 and clucky(bb)==clucky(a%100):
                        res = min(res,a-a%100+bb)
                    else:
                        #print a,bb
                        tmp = solve1(a/100,clucky(a%100)+clucky(bb))*100+bb
                        #print tmp
                        res = min(res,tmp)

    #print "Result: ",a,l,res
    return res

fi = sys.stdin
a,l = map(int,fi.readline().split())
print solve(a,l)


K = [0]*1000

K[0] = 1
for i in range(1, 1000):
    K[i] = i*K[i-1]

M = {}

def F(a,b):
    if a == 0 and b == 0:
        return 1
    if b == 0:
        return K[a]
    if (a,b) in M:
        return M[(a,b)]
    t = 0
    if a > 0:
        t += a*F(a-1,b)
    t += F(a,b-1)
    if b > 1:
        k = b-1
        for i in range(0,a+1):
            t += k*F(a-i,b-2)
            k *= (a-i)
    M[(a,b)] = t
    return t

n = int(raw_input())

d = [int(x) for x in raw_input().split(" ")]

x = 0
y = 0

for i in range(n):
    if d[i] == 1:
        x += 1
    if d[i] == 2:
        y += 1

print F(y,x)


import sys
debug = False
def solve(a, b, c, d):
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 1
    cnt2 = 0
    phases = []
    phases2 = []

    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1
            if ind2 == len(c):
                #word finished!
                cnt2 += 1
                ind2 = 0
                #check phase
                if ind1 in phases:
                    #period!
                    cnt1_, cnt2_ = phases2[phases.index(ind1)]
                    step1 = cnt1 - cnt1_
                    step2 = cnt2 - cnt2_
                    cnt = (b-cnt1)/step1
                    cnt1 += step1 * cnt
                    cnt2 += step2 * cnt
                    phases = []
                    phases2 = []
                #save phase
                phases.append(ind1)
                phases2.append([cnt1, cnt2])

        ind1 += 1
        if ind1 == len(a):
            cnt1 += 1
            ind1 = 0
            if cnt1 > b:
                return cnt2 / d
    #answ
    val2 = phases2[-1]
    val1 = phases2[phases.index(ind1)]

    step1 = val2[0] - val1[0]
    step2 = val2[1] - val1[1]

    if debug:
        print str(val1[0]) + " -- > " + str(val1[1])
        print str(val2[0]) + " -- > " + str(val2[1])

    res = step2 * b / (step1 * d)
    res = (b - val2[0]) * step2 / (step1 * d) + val2[1]
    if res < 0:
        return 0
    else:
        return res

if not debug:
    b, d = map(int, sys.stdin.readline().split())

    a = sys.stdin.readline().split()[0]
    c = sys.stdin.readline().split()[0]
    print str(solve(a, b, c, d))
else:
    vals = []
    vals.append([841, 7, 'qjqhrksmvedtqldrqgchhsofokfcovut' ,'qhtmothoulodshrfejterjlguvooccsvqrrdfqfvkqhtecuhhuqhshthrkusrc', 5])
    vals.append([933, 5, 'abaabdcbbabacbdddadbbb', 'babbadbaaadbbbbaabbaabccbbdbadbbbbbbdbcbdbaaadbdbdbbbbdcbbdcbdaadbd', 15])
    vals.append([875, 10, 'hjeaiemqfliohlicmhndhbfdmlmcnjjgbg', 'hojqhmbgjlfmlliimlhahfeihgmhhhnbmebhgnfhgmhfjqhmlnnddgmqldelnhebi', 4])
    vals.append([320672, 1, 'wyyojuothwmlvrglfzdzdbtubxuoffvncrswsaznmoijoi', 'ttvlvzxcvczuagwzgbfuwmmt', 40084])
    vals.append([5608475, 1, 'gbagadghfaedhddefgbehbbdedefbaaeddachgebhbcgahfdchffhbhfahhdegdhdfbccgefhcdhhcdfgdgfhcdffaacch', 'fgfadaaecdgabeahcacadcbfhhe', 1869491])
    vals.append([1263204, 1, 'dcbabceabbaebddaaecbddaceaedacddadadcbbadbdccdecdacdcaadbceeddccbceaade', 'abddbccbdca', 1894805])
    vals.append([100, 1, 'bca', 'abc', 99])
    vals.append([541, 9, 'bxhwcmunbdxcatppdsw', 'shbppncwbnsxxnxunwsbncpdchcbcspdcppdchmbbcuapphpdxbpcswcxpxpdscxpddbcppdxhpxbuxxdbpdpuudb', 1])
    vals.append([9447267, 1, 'cbdcbdbcdacbcabddbaabcbacbabcaacbabaccddcbbdbbaddcbcbaaadc', 'bbbbdbcbbbdbdbcdcacccbdcadadbacbcccc', 4723633])
    for val in vals:
        b, d, a, c, answer = val
        res = solve(a, b, c, d)
        if res == answer:
            print '++++++++++++++++++++++++++++'
            pass
        else:
            print '----------------------------'
            print val
            print res
            print '----------------------------'
            sys.stdin.readline()


dp=[0]*5010
dp[0]=1
n,m,k=map(int,input().split())
t=998244353
for i in range(k):
    for j in range(len(dp)-1, -1, -1):
        if j==0:dp[j]=0
        else:dp[j]=(dp[j-1]*(n-j+1)+dp[j]*j)%t
c=0
for i in range(k+1):
    c+=pow(m,max(n-i,0),t)*dp[i]
    c%=t
den=pow(m,n,t)
den=pow(den,t-2,t)
print((den*c)%t)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 10 ** 9 + 7

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

z, o = a.count(0), a.count(1)
d = pow(n * (n - 1) // 2, M - 2, M)

res = [[0] * (z + 1) for i in range(z + 1)]
tf = [[0] * (z + 1) for i in range(z + 1)]
for i in range(z + 1):
    res[i][i] = 1
    tf[i][i] = (z * (z - 1) // 2 + o * (o - 1) // 2 + i * (z - i) + (z - i) * (o - z + i)) * d % M
    if i < z: tf[i + 1][i] = (z - i) * (z - i) * d % M
    if i: tf[i - 1][i] = i * (o - z + i) * d % M

def mul(a, b):
    t = [[0] * (z + 1) for i in range(z + 1)]
    for i in range(z + 1):
        for k in range(z + 1):
            for j in range(z + 1):
                t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % M
    return t

while k:
    if k & 1:
        res = mul(res, tf)
    tf = mul(tf, tf)
    k >>= 1

v = [0] * (z + 1)
v[a[:z].count(0)] = 1
print(sum(x * y for x, y in zip(res[-1], v)) % M)


import sys

n=int(sys.stdin.readline().strip('\n'))
line=sys.stdin.readline().strip('\n').split(' ')
values=map(lambda x:int(x),line)

def evaluateBothSides(start,stop):
    print start,stop
    if stop-start==1:
        return min(values[start-1],values[stop])
    elif stop-start==0:
        return 0
    else:
        maxNum=0
        maxPos=0
        for i in xrange(start,stop):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
        return evaluateBothSides(start,maxPos)+evaluateBothSides(maxPos+1,stop)+min(values[start-1],values[stop])

def evaluateMax(stop):
    2+2

def evaluate(start,stop):
    2+2

def addToQueue(inp,queue):
    out=0
    if inp<=queue[-1]:
        queue.append(inp)
    else:
        queue.pop()
        out+=inp
        while inp>queue[-1]:
            out+=queue.pop()
        queue.append(inp)
    return out

def queueEvaluate():
    maxLeft=0
    maxRight=0
    maxPos=0
    maxNum=0
    for i in xrange(0,n):
            if values[i]>maxNum:
                maxPos=i
                maxNum=values[i]
    out=0
    queue=[maxNum]
    for i in xrange(maxPos+1,n):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxRight=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    queue=[maxNum]
    for i in xrange(maxPos-1,-1,-1):
        out+=addToQueue(values[i],queue)
        #print queue
    if len(queue)==1:
        pass
    else:
        maxLeft=queue[1]
        for i in xrange(2,len(queue)):
            out+=queue[i]
    out+=min(maxLeft,maxRight)
    return out

print queueEvaluate()


b,r = [raw_input() for _ in xrange(6)],[]
def x(i,d,c='RL'): b[i]=b[i][-d:]+b[i][:-d];r.extend([c[d>3]+str(i+1)]*(d if d<3 else 6-d))
def y(i,d): global b;b=zip(*b);x(i,d,'DU');b=zip(*b)
def u(i,j): x(j,1);y(i,1);x(j,5);y(i,5)
def p(i,j): u(i,j);x((j+5)%6,1);u((i+1)%6,j);x((j+5)%6,5);u(i,j);u(i,j)
def l(i,j): p((i+1)%6,j);p((i+3)%6,j);x(j,1)
for k,c in enumerate(sorted(''.join(b))):
    ii,jj=k%6,k/6
    z = filter(lambda x: c in x, b)[0]
    i,j=z.index(c),b.index(z)
    while i!=ii: l(i,j); i=(i+5)%6
    while j>jj: u(ii,j); j-=1
print len(r)
print '\n'.join(r)


from collections import deque
def readarray(foo): return [foo(x) for x in raw_input().split()]

stairs = []
to = []
color = []
totalcolors = 0
deg = []
priority = []

extrastairs = []
extrastair = None

def doit():
	usedstairs = set()
	visited = set([0])
	stack = []
	res = []
	nextcolor = 1

	s = 0
	if extrastair is not None:
		(s, stair) = extrastair
		visited.add(s)
		usedstairs.add(stair)
		nextcolor += 1
		res.append([0])
		res.append([stair, 0, s])

	hasnextcolor = totalcolors > nextcolor
	layer = [s]
	stack.append([s, -1, -1, 0])

	while stack:
		(u, source, parent, start) = state = stack[-1]

		nexti = None
		nexts = None
		nextv = None
		for i in xrange(start, len(to[u])):
			s = to[u][i]
			if s == source: continue
			if s in usedstairs: continue
			(v1, v2) = stairs[s]
			v = v1 if v2 == u else v2
			if not hasnextcolor and v in visited: continue
			nexti = i
			nexts = s
			nextv = v
			break

		if nexti is None:
			if parent != -1:
				layer.append(parent)
			stack.pop()
			continue

		if nextv not in visited:
			visited.add(nextv)
			layer.append(nextv)
			state[3] = nexti
			stack.append([nextv, nexts, u, 0])
			continue

		usedstairs.add(nexts)
		nextv = priority[nextcolor]
		nextcolor += 1
		hasnextcolor = totalcolors > nextcolor

		res.append(layer)
		res.append([nexts, u, nextv])
		layer = [nextv]
		visited.add(nextv)

		state[3] = nexti + 1
		stack.append([nextv, nexts, u, 0])

	res.append(layer)
	return res if not hasnextcolor else None

def colorize(s, c):
	if color[s] != -1: return
	global totalcolors
	totalcolors += 1
	color[s] = c
	deg[c] = 1
	q = deque()
	q.append(s)
	source = {s : -1}
	while q:
		u = q.popleft()
		for stair in to[u]:
			if extrastair is not None and extrastair[1] == stair: continue
			(v1, v2) = stairs[stair]
			v = v1 if v2 == u else v2
			if color[v] != -1:
				if v != source[u]:
					extrastairs.append(stair)
				continue
			color[v] = c
			source[v] = u
			deg[c] += 1
			q.append(v)

def findextrastair():
	if extrastairs: return (stairs[extrastairs[0]][0], extrastairs[0])
	for u in xrange(len(to)):
		if len(to[u]) < 2: continue
		return (u, to[u][0])
	return None

def run():
	global to, color, deg, priority, extrastair, totalcolors
	n, m = readarray(int)
	to = [[] for i in xrange(n)]
	color = [-1] * n
	deg = [0] * n
	for i in xrange(m):
		u, v = sorted(readarray(lambda x: int(x) - 1))
		stairs.append((u, v))
		to[u].append(i)
		to[v].append(i)
	for i in xrange(n):
		colorize(i, i)

	if deg[0] == 1 and n > 1:
		extrastair = findextrastair()
		if extrastair is None:
			print "NO"
			return
		color = [-1] * n
		deg = [0] * n
		totalcolors = 0
		for i in xrange(n):
			colorize(i, i)
		deg[color[extrastair[0]]] = 100500

	deg[0] = 100500
	priority = sorted(range(n), lambda x, y: deg[y] - deg[x])[:totalcolors]
	res = doit()
	if res is None:
		print "NO"
		return

	print "YES"
	print len(res) / 2
	for i, line in enumerate(res):
		if i % 2 == 0:
			print len(line),
		print " ".join(map(lambda x: str(x + 1), line))

run()


def do(i):
    if i == "(":
        return 1
    else:
        return -1
def find(i,idx):
    if i<n-idx:
        return idx+i+1
    else:
        return i-(n-idx)+1
n = input()
arr = map(do,raw_input())
s = [0]*n
s[n-1] = arr[n-1]
maxi = 0
maxv = 0
for i in range(n-1)[::-1]:
    s[i] = s[i+1] + arr[i]
    if s[i] > maxv:
        maxv = s[i]
        maxi = i
newv = arr[maxi:]+arr[:maxi]
if sum(newv) != 0:
    print 0
    print 1,1
else:
    cnt = 0
    cnt1 = -1
    cnt2 = -1
    maxv1,maxv2 = 0,0
    l1,l2,r1,r2 = 0,0,0,0
    last1,last2 = 0,0
    st = 0
    for i in range(n):
        st += newv[i]
        if st == 0:
            cnt += 1
            cnt1 = -1
            last1 = i+1

        elif st == 1:
            cnt1 += 1
            if cnt1 > maxv1:
                maxv1 = cnt1
                l1 = last1
                r1 = i+1

            last2 = i+1
            cnt2 = -1
        elif st == 2:
            cnt2 += 1
            if cnt2 > maxv2:
                maxv2 = cnt2
                l2 = last2
                r2 = i+1
    if maxv1 == 0:
        print cnt
        print 1,1
    elif maxv1>maxv2+cnt:
        print maxv1+1
        print find(l1,maxi),find(r1,maxi)
    else:
        print maxv2+cnt+1
        print find(l2,maxi),find(r2,maxi)


import array

p = 1000000007

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

d = array.array('i', 1 for _ in range(300001))
td = array.array('i', 0 for _ in range(300001))
L = b[0]
for i in range(1, n):
	if a[i - 1] != 1:
		t = m % a[i - 1]
		if L < t:
			print(0)
			exit(0)
		m //= a[i - 1]
		for j in range((L - t) // a[i - 1] + 1):
			d[j] = d[t]
			t += a[i - 1]
		L = j
	k = 0
	for j in range(L + b[i] + 1):
		if j <= L:
			k += d[j]
		k %= p
		td[j] = k
		if j >= b[i]:
			k -= d[j - b[i]]
	L += b[i]
	d, td = td, d
print(d[m] if m <= L else 0)


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(1,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)


import sys
#sys.stdin = open('game.in', 'r')
#sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = []
for i in range(50000):
	win.append([])
	for j in range(50):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) and (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) and (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


def Solve(x,B):
    if(len(B)>X):
        return False
    if(x==len(L)):
        return True
    if(Form(L[x],B)):
        A=list(B)
        for e in range(len(B)):
            r=A[e]
            A[e]=L[x]
            if(Solve(x+1,tuple(A))):
                return True
            A[e]=r
        A+=[L[x]]
        if(Solve(x+1,tuple(A))):
            return True
    return False

def Form(x,B):
    for i in range(len(B)):
        for j in range(i,len(B)):
            if(B[i]+B[j]==x):
                return True
    return False

n=int(input())
L=list(map(int,input().split()))
done=False
for X in range(1,n+1):
    if(Solve(1,(L[0],))):
        print(X)
        done=True
        break
if(not done):
    print(-1)


n = int(input())
disjointSet = [-1] * n
def root(x):
    if disjointSet[x] < 0:
        return x
    disjointSet[x] = root(disjointSet[x])
    return disjointSet[x]

def join(x, y):
    r1, r2 = root(x), root(y)
    if r1 == r2:
        return
    disjointSet[r2] = r1

points = []
vertPoints = {}
horizPoints = {}
for i in range(n):
    a, b = map(int, input().split())
    points.append((a, b))
    if a in vertPoints:
        join(i, vertPoints[a])
    else:
        vertPoints[a] = i
    if b in horizPoints:
        join(i, horizPoints[b])
    else:
        horizPoints[b] = i

sets = {}
for i in range(n):
    r = root(i)
    if r in sets:
        sets[r].append(points[i])
    else:
        sets[r] = [points[i]]

ans = 1
for i in sets:
    s = sets[i]
    horiz = [x for x,y in s]
    vert = [y for x,y in s]
    tmp = len(set(horiz)) + len(set(vert))
    if tmp <= len(s):
        ans *= 2 ** tmp
    else:
        ans *= 2 ** tmp - 1

print(ans % (10 ** 9 + 7))


# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase
from collections import Counter

def main():
    mod = 10**9+7
    r,g = map(int,input().split())
    n = 1
    while r+g >= (n*(n+1))//2:
        n += 1
    n -= 1
    tot = n*(n+1)//2
    dp = [0]*(tot+1)
    dp[0] = 1
    for i in range(1,n+1):
        for x in range(tot-i,-1,-1):
            dp[i+x] += dp[x]
            dp[i+x] %= mod
    ans = 0
    for i,val in enumerate(dp):
        if i <= r and tot-i <= g:
            ans += val
            ans %= mod
    print(ans)

#Fast IO Region
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")

if __name__ == '__main__':
    main()


import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math

# Fast IO Region
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")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split()))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split()))
#     x = 10 - n
#     print(x * (x - 1) * 3)

# for _ in range(int(input())):
#     n = int(input())
#     print(*([1] + list(range(2, n + 1))[::-1]))

# for _ in range(int(input())):
#     n = int(input())
#     s = input()
#     a = list(map(int, input().split()))
#     dp1 = [0] * n
#     dp2 = [0] * n
#     if s[0] == '1':
#         dp1[0] = a[0]
#     for i in range(1, n):
#         if s[i] == '1':
#             if s[i - 1] == '0':
#                 dp1[i] = max(dp1[i - 1], dp2[i - 1]) + a[i]
#                 dp2[i] = max(dp1[i - 1], dp2[i - 1]) + a[i - 1]
#             else:
#                 dp1[i] = max(dp1[i - 1], dp2[i - 1]) + a[i]
#                 dp2[i] = dp2[i - 1] + a[i - 1]
#         else:
#             dp1[i] = dp2[i] = max(dp1[i - 1], dp2[i - 1])
#     print(max(max(dp1), max(dp2)))

# def solve():
#     n = int(input())
#     s = list(input())
#     j = 0
#     while j < n and s[j] == '0':
#         j += 1
#     if j == n:
#         print(0)
#         return
#     s = s[j:]
#     n = len(s)
#     j = 0
#     while j < n and s[j] == '1':
#         j += 1
#     ans = s[:]
#     for i in range(j + 1):
#         b = s[:j]
#         for k in range(n - j):
#             if s[i + k] == s[j + k] == '0':
#                 b.append('0')
#             else:
#                 b.append('1')
#         ans = max(ans, b)
#     print(''.join(ans))
# solve()

def solve():
    p1, t1 = list(map(int, input().split()))
    p2, t2 = list(map(int, input().split()))
    h, s = list(map(int, input().split()))
    if t1 == t2:
        x = p1 + p2 - s
        print((h + x - 1) // x * t1)
        return
    if t1 > t2:
        p1, t1, p2, t2 = p2, t2, p1, t1
    # need = (h + p1 - s - 1) // (p1 - s) * t1
    # if need <= t2:
    #     print(need)
    #     return
    d = {}
    x1, x2, x3 = p1 - s, p2 - s, p1 + p2 - s
    d[x1] = t1
    d[x2] = t2
    a = [i * t1 for i in range(5050)]
    for i in range(1, 5001):
        j = bisect_left(a, i * t2)
        x = x1 * (j - 1 - 1) + x2 * (i - 1) + x3
        t = max(t1 * (j - 1), t2 * i)
        if x not in d:
            d[x] = t
        else:
            d[x] = max(d[x], t)
        x = x1 * (j - 1) + x2 * (i - 1) + x3
        t = max(t1 * j, t2 * i)
        if x not in d:
            d[x] = t
        else:
            d[x] = max(d[x], t)
    # for i in range(1, 5001):
    #     for j in range(1, 5001):
    #         k = max(t1 * i, t2 * j)
    #         x = x1 * (i - 1) + x2 * (j - 1) + x3
    #         if k > 10000: continue
    #         if x not in d:
    #             d[x] = k
    #         else:
    #             d[x] = max(d[x], k)
    dp = [float('inf')] * (10001)
    dp[0] = 0
    for i in range(1, 10001):
        for j in range(i):
            if i - j in d:
                dp[i] = min(dp[i], dp[j] + d[i - j])
    ans = min(dp[h:])
    print(ans)
solve()


__author__ = 'Darren'

def solve():

    def find_ways(t, n, h):
        if t == breaks and n == total:
            return 1
        if t > breaks or n == total:
            return 0
        if (t, n, h) not in dp:
            result = 0
            if t % 2 == 0:
                for i in range(h+1, 5):
                    result += find_ways(t, n+1, i)
                for i in range(1, h):
                    result += find_ways(t+1, n+1, i)
            else:
                for i in range(h+1, 5):
                    result += find_ways(t+1, n+1, i)
                for i in range(1, h):
                    result += find_ways(t, n+1, i)
            dp[(t, n, h)] = result
        return dp[(t, n, h)]

    total, humps = map(int, input().split())
    breaks = 2 * humps - 1
    dp = {}
    ans = 0
    for i in range(2, 5):
        ans += (i - 1) * find_ways(0, 2, i)
    print(ans)

if __name__ == '__main__':
    solve()


#!/usr/bin/env python

from collections import deque

Pl, Pr, Vl, Vr, k = map(int,raw_input().strip().split())

q = deque()
lucky = []
q.append(0)
lucky.append(0)
while (len(q)):
	front = q.popleft()
	x = front*10+4
	y = x+3
	if (x<=10000000000):
		q.append(x)
		lucky.append(x)
	if (y<=10000000000):
		q.append(y)
		lucky.append(y)

minl = min(Pl,Vl)
maxr = max(Pr,Vr)

mini = maxi = -1
for i in xrange(len(lucky)):
	if lucky[i] >= minl:
		mini = i
		break

for i in xrange(len(lucky)-1,0,-1):
	if lucky[i] <= maxr:
		maxi = i
		break

def intersect(x1,y1,x2,y2):
	if x1>y2 or x2>y1:
		return (1,0)
	else:
		return (max(x1,x2),min(y1,y2))

res = 0.0
inv = 1.0/(Pr-Pl+1)/(Vr-Vl+1)
for i in xrange(mini,maxi-k+2):
	left = lucky[i]
	right = lucky[i+k-1]
	pl =  intersect(Pl, Pr,lucky[i-1]+1,lucky[i])
	pr = intersect(Pl, Pr, lucky[i+k-1], lucky[i+k]-1)
	vl = intersect(Vl,Vr, lucky[i-1]+1,lucky[i])
	vr = intersect(Vl, Vr, lucky[i+k-1], lucky[i+k]-1)
	s = (pl[1]-pl[0]+1)*(vr[1]-vr[0]+1) + (vl[1]-vl[0]+1)*(pl[1]-pl[0]+1)
	if (k == 1 and (pl[0] == vr[1] or pr[1] == vl[0])):
		s = s-1
	res += inv*s

print "%.9f"%res


MOD = 1000000007

def isSubset(a, b):
	return (a & b) == a

def isIntersect(a, b):
	return (a & b) != 0

# Solve for each weakly connected component (WCC)
def cntOrder(s, t):
	p = len(s)
	m = len(t)

	inMask = [0 for i in range(m)]

	for x in range(p):
		for i in range(m):
			if t[i] % s[x] == 0:
				inMask[i] |= 1 << x

	cnt = [0 for mask in range(1<<p)]
	for mask in range(1<<p):
		for i in range(m):
			if isSubset(inMask[i], mask):
				cnt[mask] += 1

	dp = [[0 for mask in range(1<<p)] for k in range(m+1)]
	for i in range(m):
		dp[1][inMask[i]] += 1
	for k in range(m):
		for mask in range(1<<p):
			for i in range(m):
				if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):
					dp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD
			dp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD

	return dp[m][(1<<p)-1]

def dfs(u):
	global a, graph, degIn, visited, s, t

	visited[u] = True
	if degIn[u] == 0:
		s.append(a[u])
	else:
		t.append(a[u])

	for v in graph[u]:
		if not visited[v]:
			dfs(v)

def main():
	global a, graph, degIn, visited, s, t

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

	# Pre-calculate C(n, k)
	c = [[0 for j in range(n)] for i in range(n)]
	for i in range(n):
		c[i][0] = 1
		for j in range(1, i+1):
			c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD

	# Building divisibility graph
	degIn = [0 for u in range(n)]
	graph = [[] for u in range(n)]
	for u in range(n):
		for v in range(n):
			if u != v and a[v] % a[u] == 0:
				graph[u].append(v)
				graph[v].append(u)
				degIn[v] += 1

	# Solve for each WCC of divisibility graph and combine result
	ans = 1
	curLen = 0
	visited = [False for u in range(n)]
	for u in range(n):
		if not visited[u]:
			s = []
			t = []
			dfs(u)

			if len(t) > 0:
				sz = len(t) - 1
				cnt = cntOrder(s, t)

				# Number of orders for current WCC
				ans = (ans * cnt) % MOD
				# Number of ways to insert <sz> number to array of <curLen> elements
				ans = (ans * c[curLen + sz][sz]) % MOD
				curLen += sz

	print(ans)

if __name__ == "__main__":
	main()


for i in range(int(input())):
  a=list(map(int,input().split()))
  mx=max(list(map(abs,a)))
  std=(sum(list(map(lambda x:x*x,a)))/len(a))**0.5
  print('poisson'if mx/std>2 else'uniform')


import sys
range = xrange
input = raw_input

MOD = 998244353

import __pypy__
modmul = __pypy__.intop.int_mulmod
mo = lambda a,b: modmul(a,b,MOD)
po = lambda a,b: pow(a,b,MOD)

big = 10**6 + 10
modinv = [1]*big
for i in range(2,big):
    modinv[i] = mo(-(MOD//i), modinv[MOD%i])

fac = [1]
for i in range(1,big):
    fac.append(mo(fac[-1], i))

invfac = [1]
for i in range(1,big):
    invfac.append(mo(invfac[-1], modinv[i]))

def choose(n,k):
    return mo(mo(fac[n], invfac[k]), invfac[n-k])

def par(x):
    return -1 if x & 1 else 1

n = int(input())

ans = 0
for i in range(1, n + 1):
    base = -po(3, n - i)
    tmp = po(base + 1, n) - po(base, n)
    ans += par(i + 1 + n) * mo(choose(n, i), tmp)

extra = 0
for i in range(1, n + 1):
    extra += par(i + 1) * mo(choose(n, i), po(3, n * (n - i) + i))
print (3 * ans + 2 * extra) % MOD


mod = 1000000007
def power(a, p):
    res = 1
    while p > 0:
        if p % 2 == 1:
            res = (res * a) % mod
        a = (a * a) % mod
        p //= 2
    return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m))*(n-m)/n
res = res % mod
print(int(res))


#!/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))
                assert len(posibles_jefes_filtrados) == 1
                assert posibles_jefes_filtrados[0] == 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))))


import  sys
#input=sys.stdin.readline
dp={}
mod=int(1000000007)
sys.setrecursionlimit(100000)
def bigmod(n,p):
    p=int(p)
    if p==0:
        return 1
    x=bigmod(n,p/2)
    x=(x*x)%mod
    if p%2==1:
        x=(x*n)%mod
    return x
k,pa,pb=map(int,input().split())
r=bigmod(pa+pb,mod-2)
r1=bigmod(pb,mod-2)
r1=(pa*r1)%mod
p=(pa*r)%mod
q=(pb*r)%mod

def cal(k1,a1):
    if k1+a1>=k:
        return (k1+a1+r1)%mod
    if (k1,a1) in dp:
        return dp[(k1,a1)]
    dp[(k1,a1)]=((cal(k1+a1,a1)*q)%mod+(cal(k1,a1+1)*p)%mod)%mod
    return dp[(k1,a1)]

print(cal(0,1))