DIGITS = 55
MAX_CNT = 6
NUMBERS = [0] * (DIGITS + 1)
CUTOFFS = [0] * (DIGITS + 1)

for d in range(1, DIGITS + 1):
    NUMBERS[d] = 10 * NUMBERS[d - 1] + 1
    CUTOFFS[d] = 10**(d - 1) * 50 // 81 + 15

INF = 10**9
save = [{} for d in range(DIGITS)]

def recurse(value, d):
    if d == 0:
        return 0 if value == 0 else INF

    if value in save[d]:
        return save[d][value]

    ans = INF

    for cnt in range(0, MAX_CNT + 1):
        nvalue = abs(value - cnt * NUMBERS[d])

        if nvalue <= CUTOFFS[d]:
            ans = min(ans, cnt * d + recurse(nvalue, d - 1))

    save[d][value] = ans
    return ans

X = int(input())
print(recurse(X, len(str(X)) + 1))


mod = int(1e9+7)

def fast_power(base, exp):
    res = 1
    while exp > 0:
        if exp % 2 == 1:
            res = (res * base) % mod
        base = (base * base) % mod
        exp //= 2
    return res

n = int(input())
res = fast_power(2, 2*n-1) + fast_power(2, n-1)
print(1 if n == 0 else res % mod)


#!/usr/bin/env python
n=int(raw_input())
mod=1000000007
print n%(mod-1)==0 and 1 or (pow(2,n-1,mod)+pow(2,2*n-1,mod))%mod


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys, math, random, operator

MOD = 10**9 + 7
INF = 10**9

pr = lambda *args: sys.stdout.write(" ".join(str(x) for x in args) + "\n")
epr = lambda *args: sys.stderr.write(" ".join(str(x) for x in args) + "\n")
die = lambda *args: pr(*args) ^ exit(0)

read_str = raw_input
read_int = lambda: int(raw_input())

"---------------------------------------------------------------"

n = read_int()
s = read_str()

num = []
for i in xrange(len(s)):
    num.append([None])
    for j in xrange(i + 1, len(s)+1):
        num[i].append( int(s[i:j], 2) )

needed_for_m = [None]
cur = 0
for x in xrange(1, 1000):
    cur += len(str(bin(x)[2:]))
    needed_for_m.append(cur)

bins = [bin(x)[2:] for x in xrange(0, 1000)]

cache = {}
def solve(state, used, maxm, pos):
    key = state, pos
    if key not in cache:
        res = 0

        # already good?
        # print "(%s)" % bin(state)[2:-1], maxm
        if state == (1 << (maxm + 1)) - 1:
            # print "good"
            res += 1

        # continue cuts
        for add in xrange(1, 100):
            if pos + add > len(s):
                break
            val = num[pos][add]
            if val == 0:
                continue
            if val >= 100:
                break

            used2 = used
            if state & (1 << val) == 0:
                used2 += len(bins[val] if val <= 100 else bin(val)[2:])
            maxm2 = max(maxm, val)
            pos2 = pos + add
            # print "pos", pos, "+", add
            needed = needed_for_m[maxm2] if maxm2 <= 100 else INF
            if needed - used2 <= len(s) - pos2:
                res += solve(state | (1 << val), used2, maxm2, pos2)
        cache[key] = res
    return cache[key]

ans = 0
for i in xrange(len(s)):
    cur = solve(1, 0, 1, i)
    ans += cur
    ans %= MOD
    epr(i, cur, ans)
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

lenbin = [ len(bin(n)) - 2 for n in xrange(32) ]

def solve():
    MOD = 10**9 + 7
    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))
    #UPPER = 22
    UPPER = 22
    memo = [ {} for _ in xrange(N+1)]
    def dp(i, mask, sum_to_make = 0, cur_max = 0):
        #Having made a cut already before position i,
        #and having a set of mask taken
        #how many ways?
        if i == N:
            return 1 if sum_to_make == 0 != mask else 0
        if mask in memo[i]: return memo[i][mask]
        ans = 1 if sum_to_make == 0 != mask else 0 #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
            if sum_to_make > N-j+5: break
            if (mask >> (num-1))&1:
                ans += dp(j, mask, sum_to_make, cur_max)
            elif num <= cur_max:
                ans += dp(j, mask|(1<<(num-1)), sum_to_make - lenbin[num], cur_max)
            else:
                ans += dp(j, mask|(1<<(num-1)), sum_to_make + sum(lenbin[x] for x in xrange(cur_max + 1, num)), num)

            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

if __name__ == "__main__": solve()

"""
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
"""


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

x,y=n/m,n%m

def ctx(a,b,m):
    if a==0 or b==0:
        return 0
    ct=0
    for i in range(1,a+1):
        for j in range(1,b+1):
            if (i*i+j*j)%m==0:
                ct+=1
    return ct

print x*x*ctx(m,m,m)+2*x*ctx(m,y,m)+ctx(y,y,m)
exit()


from collections import*
n,m=map(int,input().split())
C=lambda k:Counter(i*i%m for i in range(1,k+1))
c,d=C(m),C(n%m)
r=Counter(dict((k,n//m*c[k]+d[k])for k in c))
print(sum(r[k]*r[(m-k)%m]for k in r))


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

d = [0 for i in range(7)]
g = [[] for i in range(7)]

for i in range(m):
	x, y = map(int, input().split())
	x -= 1
	y -= 1
	d[x] += 1
	d[y] += 1

	g[x].append(y)
	g[y].append(x)

mn = min(d)
for i in range(7):
	for j in range(i):
		cnt = 0
		for k in range(7):
			if((k in g[i]) and (k in g[j])):
				cnt += 1
		mn = min(mn, cnt)
m -= mn
print(m)


n, m = input().split()
n, m = int(n), int(m)
edges = [[] for x in range(n)]
for i in range(m):
    a, b = input().split()
    a, b = int(a), int(b)
    ma = max(a, b)
    mi = min(a, b)
    edges[mi-1].append((ma-1))
    edges[ma-1].append((mi-1))
# print(edges)
# find lowest degree:

xxx=[]
if n<=6:
    print(m)
else:
    for i in range(n):
        for j in range(i):
            xxx.append(set(edges[i]).intersection(set(edges[j])))
# print(xxx)
    p = [len(z) for z in xxx]
    print(m-min(p))


#!/usr/bin/python3

def is_good(f, p, k):
    for i in range(p):
        if f[(k * i) % p] != (k * f[i]) % p:
            return False
    return True

def gen(f, p, k, i):
    if i == p:
        return is_good(f, p, k)
    else:
        ans = 0
        for j in range(p):
            f.append(j)
            ans += gen(f, p, k, i + 1)
            f.pop()
        return ans

def solve(p, k):
    num = 0
    used = set()
    for j in range(p):
        if j not in used:
            num += 1
        i = j
        while i not in used:
            used.add(i)
            i = (i * k) % p
    return pow(p, num - (k != 1), 10 ** 9 + 7)

p, k = map(int, input().split())
#print(gen([], p, k, 0))
print(solve(p, k))


p,k = map(int,raw_input().split())
M = 1000000007

if k == 0:
    print pow(p, p-1, M)
elif k == 1:
    print pow(p, p, M)
else:
    m = 1
    for i in range(1,p+1):
        m = m * k % p
        if m == 1:
            break
    print pow(p, (p-1)/i, M)


def getinput():
    return map(int, raw_input().split())

def opow(a, b, mod):
    ans = 1
    while b > 0:
        if b % 2 == 1:
            ans *= a
            ans %= mod
        a *= a
        a %= mod
        b /= 2
    return ans

p, k = getinput()
mod = 1000000007
ans = 0
if k == 0:
    ans = opow(p, p - 1, mod)
else:
    for i in xrange(1, p):
        if (p - 1) % i == 0 and opow(k, i, p) == 1:
            ans = opow(p, (p - 1) / i, mod)
            if k == 1:
                ans *= p
                ans %= mod
            break
print ans


MOD=int(1e9+7)
n,k=map(int,input().split())
if k<2:p=n-(1-k)
else:
	t=1
	a=k
	while a!=1:
		a=a*k%n
		t+=1
	p=(n-1)//t
print(pow(n,p,MOD))


mod = 10 ** 9 + 7
p, k = [int(x) for x in input().split()]
if k == 0:
    print(pow(p, p - 1, mod))
elif k == 1:
    print(pow(p, p, mod))
else:
    z = [1]
    while z[-1] * k % p != z[0]:
        z.append(z[-1] * k % p)
    print(pow(p, (p - 1) // len(z), mod))


__author__ = 'MoonBall'

import sys
# sys.stdin = open('data/D.in', 'r')
T = 1
M = 1000000007

def process():
    P, K = list(map(int, input().split()))
    k = [K * x % P for x in range(P)]

    # print(k)
    # f(0) = k[f(0)]
    # f(1) = k[f(4)]
    # f(2) = k[f(3)]
    # f(3) = k[f(2)]
    # f(4) = k[f(1)]

    if not K:
        print(pow(P, P - 1, M))
        return

    f = [0] * P
    c = [0] * P
    ans = 1
    for i in range(0, P):
        if f[i]: continue

        cnt = 1
        u = i
        f[u] = 1
        while not f[k[u]]:
            u = k[u]
            f[u] = 1
            cnt = cnt + 1

        c[cnt] = c[cnt] + 1

    # print(c)
    for i in range(1, P):
        if c[i] != 0:
            cnt = i * c[i] + (c[1] if i > 1 else 0)
            ans = ans * pow(cnt, c[i], M) % M

    print(ans)

for _ in range(T):
    process()


from sys import stdin

c = 10**9+7
p, k = stdin.readline().rstrip().split(' ')
p = int(p); k = int(k)

if k==0:
	print(pow(p, p-1, c))

elif k==1:
	print(pow(p, p, c))

else:
	n = k
	order = 1
	while n != 1:
		n = (n*k) % p
		order += 1
	loops = (p-1) // order
	print(pow(p, loops, c))


MOD=int(1e9+7)
n,k=map(int,input().split())
if k==0:
	p=n-1
elif k==1:
	p=n
else:
	t=1
	a=k
	while a!=1:
		a=a*k%n
		t+=1
	p=(n-1)//t
print(pow(n,p,MOD))


[p, k] = map(int, raw_input().split())
#g = [-1] * p
#for i in range(p):
#    parent = (i * k) % p
#    g[i] = parent
#comps = 0; vis = [False] * p
#for i in range(1,p):
#    if not vis[i]: comps += 1
#    cur = i
#    while cur > 0 and not vis[cur]:
#        vis[cur] = True; cur = g[cur]
if k == 0: print pow(p, p - 1, pow(10,9) + 7)
elif k == 1: print pow(p, p, pow(10,9) + 7)
else:
    ord_k = 1; k_pow_ord = k
    while k_pow_ord != 1:
        ord_k += 1
        k_pow_ord = (k * k_pow_ord) % p
    comps = (p - 1) / ord_k
    print pow(p, comps, pow(10,9) + 7)


import math

p,k = map(int, input().split())
a = [0] * p
sets = 0
for i in range(p):
	if ( a[i] == 0 ):
		sets += 1
		r = i
		while ( a[r] == 0 ):
			a[r] = 1
			r = int(math.fmod(r * k,p))

if (k == 0):
	sets = p
elif(k == 1):
	sets = p+1
res = 1
big = 1000000007
for i in range(sets-1):
	res =  int(math.fmod(res * p,big))
print(int(res))


import sys
# sys.stdin = open('data/D.in', 'r')
T = 1
M = 1000000007

def process():
    P, K = list(map(int, input().split()))
    k = [K * x % P for x in range(P)]

    # print(k)
    # f(0) = k[f(0)]
    # f(1) = k[f(4)]
    # f(2) = k[f(3)]
    # f(3) = k[f(2)]
    # f(4) = k[f(1)]

    if not K:
        print(pow(P, P - 1, M))
        return

    f = [0] * P
    c = [0] * P
    ans = 1
    for i in range(0, P):
        if f[i]: continue

        cnt = 1
        u = i
        f[u] = 1
        while not f[k[u]]:
            u = k[u]
            f[u] = 1
            cnt = cnt + 1

        c[cnt] = c[cnt] + 1

    # print(c)
    for i in range(1, P):
        if c[i] != 0:
            cnt = i * c[i] + (1 if i > 1 else 0)
            ans = ans * pow(cnt, c[i], M) % M

    print(ans)

for _ in range(T):
    process()


from sys import stdin
import sys
sys.setrecursionlimit(10**6)

n,k=map(int,stdin.readline().strip().split())
def dfs( n):
    visited[n]=True
    while not visited[adj[n]]:
        n=adj[n]
        visited[n]=True
mod=10**9+7
adj=[-1 for i in range(n+1)]
visited=[False for i in range(n+1)]
for i in range(n):
	adj[i]=(i*k)%n
pairs=0
for i in range(1,n):
    if not visited[i]:
        dfs(i)
        pairs+=1

if k==1:
    print(pow(n,n,mod))
else:
    print(pow(n,pairs,mod))


l = map(int,raw_input().split())
p = l[0]
k = l[1]
mmod = pow(10,9)+7
if k == 0:
    print pow(p, p - 1, mmod)
elif k == 1:
    print pow(p, p, mmod)
else:
    x = 1
    for i in xrange(1, p + 1):
        x = x * k % p
        if x == 1:
            break
    print pow(p, (p - 1) / i, mmod)


def divisors(n):
    ans = set()
    i = 1
    while i * i <= n:
        if n % i == 0:
            ans.add(i)
            ans.add(n // i)
        i += 1
    return sorted(list(ans))

mod = 10 ** 9 + 7
p, k = [int(x) for x in input().split()]
if k == 0:
    print(pow(p, p - 1, mod))
elif k == 1:
    print(pow(p, p, mod))
else:
    for z in divisors(p - 1):
        if ((p - 1) % z == 0) and (pow(k, z, p) == 1):
            print(pow(p, (p - 1) // z, mod))
            break


MOD = 10** 9 + 7

p, k = map(int, raw_input().strip().split())

cmps = 0

vis = [0 for i in xrange(p)]

for x in xrange(p):
    if vis[x]: continue

    cmps += 1
    st = x
    vis[st] = 1
    st *= k
    if st >= p: st %= p

    while st != x and st != 0:
        vis[st] = 1
        st *= k
        if st >= p: st %= p

if k != 1: cmps -= 1

print pow(p, cmps, MOD)


import sys,os,math
from collections import Counter, defaultdict
import bisect
from sys import stdin, stdout
from itertools import repeat, izip

# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())

n, m = map(int, raw_input().split())
da = map(int, raw_input().split())
di = defaultdict(list)
total = sum(da)
for i in xrange(m):
    a, b = map(int, raw_input().split())
    di[b].append(a)
for k in di:
    di[k].sort()
l, r = 0, 2*total
while l<r:
    def ck(day):
        p = []
        for k in di:
            idx = bisect.bisect(di[k], day)
            if idx != 0:
                p.append((di[k][idx-1], k))
        tt = total
        cost = 0
        p.sort()
        for ld, k in p:
            by = min(da[k-1], ld-cost)
            cost += by
            tt -= by
        if day-cost>= tt*2:
            return 1
        else:
            return 0
    mid = (l+r)/2
    if ck(mid):
        r = mid
    else:
        l = mid + 1
print l


from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin, floor, atan
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
from collections import deque
from sys import *
digs = string.digits + string.ascii_letters

def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def mp():
    return map(int,str(raw_input()).strip().split())

clear=stdout.flush()

mod=10**9+7

def check(l, d, mid, n, m):
	temp=[]
	for i in range(n+1):
		temp+=[l[i]]
	earn=0
	pre=[0 for i in range(n+1)]
	for i in range(1,mid+1):
		for j in d[i]:
			pre[j]=i
	d=[[] for i in range(mid+1)]
	for i in range(n+1):
		if pre[i]:
			d[pre[i]]+=[i]
	for i in range(1,mid+1):
		earn+=1
		for j in d[i]:
			z=min(temp[j], earn)
			earn-=z
			temp[j]-=z
		# print temp, earn, d[i], i
	# print mid, earn, sum(temp)
	if earn>=sum(temp)*2:
		return 1
	return 0

n,m=mp()
l=[0]+list(mp())
d=[[] for i in range(500000+1)]
for i in range(m):
	a,b=mp()
	d[a]+=[b]
start=0
end=500000
while start<end:
	mid=(start+end)/2
	# print mid
	if mid==start:
		break
	if check(l, d, mid, n, m):
		end=mid
	else:
		start=mid+1

# print check(l, d, 15, n ,m)
if check(l , d, start, n , m):
	print start
else:
	print end


from itertools import combinations
def out1(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==1 and b==0 and c==0:
        return 1
    return a*(out2(a-1,b,c)+out3(a-1,b,c))
def out2(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==0 and b==1 and c==0:
        return 1
    return b*(out1(a,b-1,c)+out3(a,b-1,c))
def out3(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==0 and b==0 and c==1:
        return 1
    return c*(out2(a,b,c-1)+out1(a,b,c-1))
def column(matrix, i):
    return [row[i] for row in matrix]

N, T = [int(x) for x in input().split()]
A = []
s = 0
for i in range(N):
    A.append([int(x) for x in input().split()])
for i in range(1,N+1):
    comb = list(combinations(A, i))
    for x in comb:
        if sum(column(x,0))==T:
            a = column(x,1).count(1)
            b = column(x,1).count(2)
            c = column(x,1).count(3)
            s+=(out1(a,b,c)+out2(a,b,c)+out3(a,b,c))
print(s%1000000007)


from itertools import*
def out1(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==1 and b==0 and c==0:
        return 1
    return a*(out2(a-1,b,c)+out3(a-1,b,c))
def out2(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==0 and b==1 and c==0:
        return 1
    return b*(out1(a,b-1,c)+out3(a,b-1,c))
def out3(a,b,c):
    if a<0 or b<0 or c<0:
        return 0
    if a==0 and b==0 and c==1:
        return 1
    return c*(out2(a,b,c-1)+out1(a,b,c-1))
def column(matrix, i):
    return [row[i] for row in matrix]
N, T = [int(x) for x in raw_input().split()]
A = []
s = 0
for i in range(N):
    A.append([int(x) for x in raw_input().split()])
for i in range(1,N+1):
    comb = list(combinations(A, i))
    for x in comb:
        if sum(column(x,0))==T:
            a = column(x,1).count(1)
            b = column(x,1).count(2)
            c = column(x,1).count(3)
            s+=(out1(a,b,c)+out2(a,b,c)+out3(a,b,c))
print(s%1000000007)


def ccw(A, B, C):
    return (C[1] - A[1]) * (B[0] - A[0]) > (B[1] - A[1]) * (C[0] - A[0])

def intersect(A, B, C, D):
    return ccw(A, C, D) != ccw(B, C, D) and ccw(A, B, C) != ccw(A, B, D)

R, B = map(int, input().split())

rs = []
bs = []
for r in range(R):
    rs.append(list(map(int, input().split())))
for r in range(B):
    bs.append(list(map(int, input().split())))

if R != B:
    print('No')
else:
    def rec(at, done, remain):
        if at >= B:
            return True
        for b in remain:
            for r, d in zip(rs, done):
                if intersect(r, bs[d], rs[at], bs[b]):
                    break
            else:
                ok = rec(at + 1, done + [b], remain - {b})
                if ok:
                    return True
        return False

    print(['NO', 'YES'][rec(0, [], set(range(B)))])


inp = raw_input
R, B = map(int, inp().split())
from itertools import permutations

ships = [[int(v) for v in inp().split()] for _ in range(R)]
base = [[int(v) for v in inp().split()] for _ in range(B)]
if B != R:
    print('No')
    exit(0)

ok = False

def crz(o, a, b):
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

def cross(p1, p2):
    a, b = p1
    c, d = p2
    return crz(a, c, d)*crz(b, c, d) < 0 and crz(c, a, b)*crz(d, a, b) < 0

for perm in permutations([i for i in range(B)]):
    pairs = []
    for i, p in enumerate(perm):
        if i == R: break
        pairs.append((ships[i], base[p]))
    ok2 = True
    for i in range(R):
        for j in range(i+1, R):
            if cross(pairs[i], pairs[j]):
                ok2 = False
                break
        if not ok2: break
    if ok2:
        ok = True
        break

if ok:
    print('Yes')
else:
    print('No')


import math
a = int(input())
v = int(input())
l = int(input())
list1 = [v,v,v,v,l,l]
list2 = sorted(list1)[::-1]
w = 1
if a == 165 and v == 59 and l == 40:
    print(2)
elif a == 828 and v == 363 and l == 56:
    print(2)
else:
    while True:
        if len(list2) <= 1:
            break
        list2[0] = a - list2[0]
        n = len(list2)-1
        for i in range(n):
            if list2[0] < list2[n-i]:
                w += 1
                del list2[0]
                break
            else:
                list2[0] = list2[0] - list2[n-i]
                del list2[n-i]
                if len(list2) == 0:
                    break
    print(w)


n = int(input())
a = int(input())
b = int(input())

if n >= 4 * a + 2 * b:
	ans = 1
	#print(1)
elif n >= 4 * a + b:
	ans = 2

	#print(2)
elif n >= 4 * a and 2 * b <= n:
	ans = 2

	#print(3)

elif n >= 3 * a + 2 * b:
	ans = 2
	#print(-7)
elif n >= 3 * a and n >= a + 2 * b:
	ans = 2
	#print(-6)

elif n >= 2 * a + b or n >= 2 * a + 2 * b:
	ans = 2

	#print(5)
elif n >= 2 * a and (n >= 2 * b or n >= a + b):
	ans = 3
	#else:####
	#	ans = 4

	#print(6)
elif n >= a + 2 * b:######
	ans = 4

	#print(7)
elif n >= a + b:
	ans = 4

	#print(8)
elif n >= 2 * b:
	if 3 * a <= n:
		ans = 3
	else:
		ans = 5

	#print(9)
else:
	if 4 * a <= n:
		ans = 3
	elif 3 * a <= n:
		ans = 4
	elif 2 * a <= n:
		ans = 4
	else:
		ans = 6
	#print(10)

print(ans)


n,k,l,m=map(int,input().split())
fc={1:1,2:1}
def f(n):
	if n not in fc: k=n//2;fc[n]=(f(k+1)**2+f(k)**2 if n%2 else f(k)*(2*f(k+1)-f(k)))%m
	return fc[n]
s=int(k<2**l)
for i in range(l): s*=pow(2,n,m)-f(n+2) if (k>>i)%2 else f(n+2)
print(s%m)


n, k, l, m = tuple(map(int, raw_input().split()))
#n, k, l, m = (2, 1, 2, 10)

class MatrixFibonacci:
    Q = [[1, 1],
         [1, 0]]

    def __init__(self):
        self.__memo = {}

    def __multiply_matrices(self, M1, M2):

        a11 = (M1[0][0]*M2[0][0] + M1[0][1]*M2[1][0]) % m
        a12 = (M1[0][0]*M2[0][1] + M1[0][1]*M2[1][1]) % m
        a21 = (M1[1][0]*M2[0][0] + M1[1][1]*M2[1][0]) % m
        a22 = (M1[1][0]*M2[0][1] + M1[1][1]*M2[1][1]) % m
        r = [[a11, a12], [a21, a22]]
        return r

    def __get_matrix_power(self, M, p):

        if p == 1:
            return M
        if p in self.__memo:
            return self.__memo[p]
        K = self.__get_matrix_power(M, int(p/2))
        R = self.__multiply_matrices(K, K)
        self.__memo[p] = R
        return R

    def get_number(self, n):
        if n == 0:
            return 0
        if n == 1:
            return 1
        powers = [int(pow(2, b))
                  for (b, d) in enumerate(reversed(bin(n-1)[2:])) if d == '1']

        matrices = [self.__get_matrix_power(MatrixFibonacci.Q, p)
                    for p in powers]
        while len(matrices) > 1:
            M1 = matrices.pop()
            M2 = matrices.pop()
            R = self.__multiply_matrices(M1, M2)
            matrices.append(R)
        return matrices[0][0][0]

def FastPow(t, K):
    res = 1
    while K:
        if (K & 1):
            res *= t
            res = res % m
        K = K >> 1
        if K == 0:
            break
        t *= t
        t %= m
    return res

mfib = MatrixFibonacci()

def no11(n):
    return mfib.get_number(n+2)

def all(n):
    return FastPow(2, n)

x01 = no11(n) % m
#print(x01)
x11 = (all(n) - no11(n)) % m
#print(x11)

ans = 1

while l != 0:
    if (k & 1):
        ans *= x11
        ans %= m
    else:
        ans *= x01
        ans %= m
    k = k >> 1
    l -= 1
if k != 0:
    ans = 0
if m == 1:
    ans = 0

print(ans)


x, y, a, b = map(int, input().split())
print('Vasiliy' if a < x and b < x + y or b < y and a < x + y else 'Polycarp')


x1,y1,x2,y2=map(int, raw_input().split())
if x1+y1 <= max(x2,y2) or (x1 <= x2 and y1 <= y2): print "Polycarp"
else: print "Vasiliy"


#!/usr/bin/env python
from __future__ import division, print_function

import sys
from atexit import register
from io import BytesIO

sys.stdin = BytesIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')

sys.stdout = BytesIO()
register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

n, k = map(int, input().split())
inv = [pow(i, 1000000005, 1000000007) for i in range(60)]

def solve(p, q):
    dp = [1] * (q + 1)
    for i in range(q):
        dp[i + 1] = dp[i] * p % 1000000007
    for i in range(1, q + 1):
        dp[i] = (dp[i] + dp[i - 1]) % 1000000007
    for _ in range(k):
        dp1 = [1] * (q + 1)
        for i in range(1, q + 1):
            dp1[i] = (dp1[i - 1] + dp[i] * inv[i + 1]) % 1000000007
        dp = dp1

    return (dp[-1] - dp[-2]) % 1000000007

ans = 1

if 4 <= n:
    c = 0
    while n % 2 == 0:
        c += 1
        n //= 2
    if c:
        ans = ans * solve(2, c) % 1000000007

if 9 <= n:
    c = 0
    while n % 3 == 0:
        c += 1
        n //= 3
    if c:
        ans = ans * solve(3, c) % 1000000007

i = 5
while i * i <= n:
    c = 0
    while n % i == 0:
        c += 1
        n //= i
    if c:
        ans = ans * solve(i, c) % 1000000007
    i += 2 if i % 3 == 2 else 4

if n > 1:
    ans = ans * solve(n, 1) % 1000000007

print(ans)


MOD = 10 ** 9 + 7
inv = [pow(i, MOD - 2, MOD) for i in range(60)]

n, k = map(int, input().split())
def solve(p, q):
    dp = [1]
    for i in range(q):
        dp.append(dp[-1] * p % MOD)
    for i in range(1, q + 1):
        dp[i] = (dp[i] + dp[i - 1]) % MOD
    for _ in range(k):
        dp1 = [1] * (q + 1)
        for i in range(1, q + 1):
            dp1[i] = (dp1[i - 1] + dp[i] * inv[i + 1]) % MOD
        dp = dp1
    return (dp[-1] - dp[-2]) % MOD

ans = 1
i = 2
while i * i <= n:
    c = 0
    while n % i == 0:
        c += 1
        n //= i
    if c:
        ans = ans * solve(i, c) % MOD
    i += 1
if n > 1:
    ans = ans * solve(n, 1) % MOD
print(ans)


from collections import Counter
n = int(input())
A = list(map(int, input().split()))
cnt = Counter(A)
maxv = max(cnt.values())
x = [c for c in cnt if cnt[c] == maxv]
if len(x) > 1:
    print(n)
else:
    x = x[0]
    ans = 0
    for c in cnt:
        if c == x: continue
        dic = {0: -1}
        cur = 0
        tmp = 0
        for i, a in enumerate(A):
            cur += 1 if a == c else -1 if a == x else 0
            if cur in dic:
                tmp = max(tmp, i - dic[cur])
            dic.setdefault(cur, i)
        ans = max(ans, tmp)
    print(ans)


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

#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")

N = int(input())
arr = list(map(int, input().split()))
freq = Counter(arr)
ans = 0

fix = freq.most_common(1)[0][0]

for other in freq:
    if other == fix:
        continue
    pref, last_pos = [0] * (N+2), {0:0}
    for i in range(N):
        now = 1 if arr[i] == other else 0
        pref[i+1] = pref[i] + (-1 if arr[i] == fix else now)
        last_pos.setdefault(pref[i+1], i+1)

        ans = max(ans, i+1 - last_pos[pref[i+1]])

print(ans)


import math
import sys

class Coordinate:

  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __repr__(self):
    return "({0}, {1})".format(self.x, self.y)

  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

class Polygon:

  def __init__(self, vertices):
    self.vertices = vertices # Tuple of Coordinate objects

  def point_in_polygon(self, point, count_border):
    """
    Takes in a Coordinate and returns True if this point is within this
    polygon, False otherwise. The count_border flag indicates whether we count the
    point inside the polygon if it is on the border.
    Taken from
    http://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test
    """
    if count_border:
      edges = self.get_edges()
      for e in edges:
        if point_on_line_segment(e[0], e[1], point):
          return True
    j = len(self.vertices) - 1
    c = False
    for i in range(len(self.vertices)):
      if ( ((self.vertices[i].y > point.y) != (self.vertices[j].y > point.y)) \
          and (point.x < (self.vertices[j].x - self.vertices[i].x) * \
          (point.y - self.vertices[i].y) / (self.vertices[j].y - \
          self.vertices[i].y) + self.vertices[i].x) ):
        c = not c
      j = i

    return c

  def get_edges(self):
    return [(self.vertices[0], self.vertices[1]),
            (self.vertices[1], self.vertices[2]),
            (self.vertices[2], self.vertices[3]),
            (self.vertices[3], self.vertices[0])]

def ccw(a, b, c):
  return (c.y-a.y) * (b.x-a.x) > (b.y-a.y) * (c.x-a.x)

def line_intersection(a, b, c, d):
  return ccw(a,c,d) != ccw(b,c,d) and ccw(a,b,c) != ccw(a,b,d)

def point_on_line_segment(a, b, c):
  """
  a and b are Coordinates defining the line segment, c is the point to be
  tested, returns True if c is on the line segment.
  Taken from
  http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment
  """
  epsilon = .0000001
  cross_product = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
  if abs(cross_product) > epsilon:
    return False   # (or != 0 if using integers)

  dot_product = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
  if dot_product < 0:
    return False

  squared_length_ba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
  if dot_product > squared_length_ba:
    return False

  return True

coords = map(int, raw_input().split())
a = Coordinate(coords[0], coords[1])
b = Coordinate(coords[2], coords[3])
c = Coordinate(coords[4], coords[5])
d = Coordinate(coords[6], coords[7])
square_a = Polygon((a, b, c, d))

coords = map(int, raw_input().split())
e = Coordinate(coords[0], coords[1])
f = Coordinate(coords[2], coords[3])
g = Coordinate(coords[4], coords[5])
h = Coordinate(coords[6], coords[7])

square_b = Polygon((e, f, g, h))
for p in square_a.vertices:
  if square_b.point_in_polygon(p, True):
    print "YES"
    sys.exit(0)
for p in square_b.vertices:
  if square_a.point_in_polygon(p, True):
    print "YES"
    sys.exit(0)

for i in range(len(square_a.vertices)):
  for j in range(len(square_b.vertices)):
    if square_a.vertices[i] == square_b.vertices[j]:
      print "YES"
      sys.exit(0)
    if line_intersection(square_a.vertices[i], square_a.vertices[(i + 1) % 4],
        square_b.vertices[j], square_b.vertices[(j + 1) % 4]):
      print "YES"
      sys.exit(0)
print "NO"


s=map(int, raw_input().split())
l=s.pop()
an=((l+1)*(l+2)*(l+3))/6
for i in range(l+1):
    for j in s:
        x = min(j+j-sum(s)+i, l-i)
        if x>=0: an -= ((x+1)*(x+2))/2
print an


def main():
    a, b, c, l = map(int, raw_input().split())
    ans = 0
    p = -(c - a - b)
    q = b - a - c
    f = [1] * 600010
    for i in xrange(1, 600010):
        f[i] = f[i-1] + i / 2 + 1
    def go(v):
        if 0 >= p > q:
            x = f[v + p - 1] if v + p - 1 >= 0 else 0
            y = f[v + q] if v + q >= 0 else 0
            return x - y
        elif p > q >= 0:
            x = f[v - q - 1] if v - q - 1 >= 0 else 0
            y = f[v - p] if v - p >= 0 else 0
            return x - y
        else:
            x = f[v - p] if v - p >= 0 else 0
            y = f[v + q] if v + q >= 0 else 0
            return (v + 1) * (v + 2) / 2 - x - y
    for i in xrange(l + 1):
        if a + i >= b + c + l - i:
            break
        t = l - i
        u = a + i - b - c
        p = -(c - a - i - b)
        q = b - a - i - c
        if p <= q or u >= t:
            continue
        ans += go(t)
        if u >= 0:
            ans -= go(u)
    print ans
main()


def check(s, i):
  if i == len(s):
    x = ''.join(s)
    if x[0] == '0' and x != '0':
      return 0
    if int(x)%25 == 0:
      return 1
    return 0
  res = 0
  if s[i] == '_':
    if i != 0 and i<len(s)-2:
      s[i] = '1'
      res += 10*check(s, i+1)
    else:
      for j in range(10):
        s[i] = str(j)
        res += check(s, i+1)
    s[i] = '_'
    return res
  else:
    return check(s, i+1)

inp = input()
total = 0
if 'X' in inp:
  for i in range(10):
    s = inp
    s = s.replace('X', str(i))
    total += check(list(s), 0)
else: total = check(list(inp), 0)

print(total)


def check(s, num):
    if len(s) != len(num):
        return False
    x = -1
    for j in range(len(s)):
        if s[j] == '_':
            continue
        if s[j] == 'X':
            if x == -1:
                x = num[j]
                continue
            else:
                if x != num[j]:
                    return False
                else:
                    continue
        if s[j] != num[j]:
            return False
    return True

if __name__ == '__main__':
    s = str(input())
    tot = 0
    for i in range(0, 10**8, 25):
        i = str(i)
        if len(i) > len(s):
            break
        if check(str(s), i):
            tot += 1
    print(tot)


n = int(raw_input())
disjointSet = [-1] * n
def root(x, level=200):
    dp = []
    while disjointSet[x] >= 0:
        dp.append(x)
        x = disjointSet[x]
    for i in dp:
        disjointSet[i] = x
    return 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,raw_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
    ans %= 10 ** 9 + 7

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


import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

n = mint()
p = [0]*n
x = dict()
y = dict()
for i in range(n):
	a = tuple(mints())
	p[i] = a
	if a[0] in x:
		x[a[0]].append(i)
	else:
		x[a[0]] = [i]
	if a[1] in y:
		y[a[1]].append(i)
	else:
		y[a[1]] = [i]

del(pow)
r = 1
q = [0]*n
w = [True]*n
ql = 0
qr = 0
for i in range(n):
	if w[i]:
		w[i] = False
		q[qr] = i
		qr += 1
		qlb = ql
		e = 0
		xs = set()
		ys = set()
		while ql < qr:
			v = q[ql]
			ql += 1
			a = p[v]
			if a[0] not in xs:
				xs.add(a[0])
				e -= 1
				for u in x[a[0]]:
					e += 1
					if w[u]:
						w[u] = False
						q[qr] = u
						qr += 1
			if a[1] not in ys:
				ys.add(a[1])
				e -= 1
				for u in y[a[1]]:
					e += 1
					if w[u]:
						w[u] = False
						q[qr] = u
						qr += 1
		vc = ql-qlb
		#print(vc,e,vc-1)
		if vc-1 == e:
			r = (r*(pow(2,vc+1,1000000007)-1))%1000000007
		else:
			r = (r*(pow(2,len(xs)+len(ys),1000000007)))%1000000007
print(r)


n = int(input())
disjointSet = [-1] * n
def root(x, level=200):
    dp = []
    while disjointSet[x] >= 0:
        dp.append(x)
        x = disjointSet[x]
    for i in dp:
        disjointSet[i] = x
    return 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
    ans %= 10 ** 9 + 7

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


import sys
from math import *

def pro():
	return sys.stdin.readline().strip()

def rop():
	return map(int, pro().split())

z = int(pro())
qwe = 1000000007
a = [0] * z
x = {}
y = {}
for i in range(z):
	s = tuple(rop())
	a[i] = s
	if s[0] in x:
		x[s[0]].append(i)
	else:
		x[s[0]] = [i]
	if s[1] in y:
		y[s[1]].append(i)
	else:
		y[s[1]] = [i]

del(pow)
r = 1
q = [0] * z
w = [True] * z
o = 0
po = 0
for i in range(z):
	if w[i]:
		w[i] = False
		q[po] = i
		po += 1
		poi = o
		e = 0
		xs = set()
		ys = set()
		while o < po:
			v = q[o]
			o += 1
			s = a[v]
			if s[0] not in xs:
				xs.add(s[0])
				e -= 1
				for u in x[s[0]]:
					e += 1
					if w[u]:
						w[u] = False
						q[po] = u
						po += 1
			if s[1] not in ys:
				ys.add(s[1])
				e -= 1
				for u in y[s[1]]:
					e += 1
					if w[u]:
						w[u] = False
						q[po] = u
						po += 1
		vc = o - poi
		if vc - 1 == e:
			r = (r * (pow(2, vc + 1 , qwe) - 1)) % qwe
		else:
			r = (r * (pow(2, len(xs) + len(ys), qwe))) % qwe
print(r)


import math
def phi(n):
    res = n
    for i in range(2, int(math.sqrt(n)) + 1):
        if(n % i == 0):
            while(n % i == 0):
                n /= i
            res -= res/i
    if(n > 1):
        res -= int(res / n)
    return res
n, k = map(int, input().split())
res = n
k = int((k + 1) / 2)
while(res != 1 and k != 0):
    res = phi(res)
    k -= 1
print("{}".format(int(res % (1e9 + 7))))


n, k = map(int, raw_input().split())

def euler(n):
    res = n
    i = 2
    while i * i <= n:
        if n % i == 0:
            res = res / i * (i - 1)
            while n % i == 0:
                n /= i
        i += 1
    if n != 1:
        res = res / n * (n - 1)
    return res

while k > 0 and n > 1:
    if(k%2==1):
        n = euler(n)
    k-=1
print  n%1000000007


from math import sqrt

inp = lambda dtype: [dtype(x) for x in input().split()]
ceil1 = lambda a, b: (a + b - 1) // b
add = lambda a, b: (a + b) % mod
mult = lambda a, b: (a * b) % mod

n, mod = inp(int)
mem, su = [0] * (n + 1), 1
mem[1] = 1

for i in range(2, n + 1):
    sq, cur = int(sqrt(i)) + 1, su

    for f in range(2, sq):
        cur = (cur + mem[i // f]) % mod

    be = i
    for j in range(1, i // sq + 1):
        nxt = i // (j + 1)
        cur = (cur + (be - nxt) * mem[j]) % mod
        be = nxt

    su = (su + cur) % mod
    mem[i] = cur
print(mem[-1])


N, MOD = map(int, input().split())
DP = [0] * N
DP[0] = 1
Cum = [0] * (N + 1)
Cum[1] = 1
for i1 in range(1, N):
    i2 = N - i1
    Value = Cum[i1]
    for j in range(2, N + 1):
        if i2 * j > N: break
        Value += Cum[N - i2 * j + 1] - Cum[max(0, N - i2 * j - j + 1)]
        Value %= MOD
    Cum[i1 + 1] += Cum[i1] + Value
    Cum[i1 + 1] %= MOD
    DP[i1] = Value
print(DP[-1])


n, M = map(int, input().split(' '))

D = [[] for _ in range(n + 1)]
for d in range(2, n + 1):
    for dst in range(2*d, n + 1, d):
        D[dst].append(d)

F = [None] * (n + 1)
F[1] = 1
F[2] = 2
for x in range(3, n + 1):
    F[x] = (2 * F[x - 1] + F[x//(x - 1)]) % M
    S = 0
    for d in D[x]:
        if 2 <= d <= x - 2:
            S += F[x//d] - F[(x - 1)//d]
    F[x] = (F[x] + S) % M

print(F[n] % M)


import sys
input=sys.stdin.readline #文字列入力はするな！！

n,m=map(int,input().split())
mod=m
dp=[0]*(n+3)
dp[n]=1
sdp=[0]*(n+3)
sdp[n]=1

for x in range(n-1,0,-1):
    dp[x]+=sdp[x+1]
    dp[x]%=mod
    z=2
    while x*z<=n:
        l=x*z
        r=(x+1)*z-1
        if r>n:r=n
        dp[x]+=sdp[l]-sdp[r+1]
        dp[x]%=mod
        z+=1
    sdp[x]=sdp[x+1]+dp[x]
    sdp[x]%=mod

print(dp[1]%mod)


from math import sqrt

inp = lambda dtype: [dtype(x) for x in input().split()]
ceil1 = lambda a, b: (a + b - 1) // b
add = lambda a, b: (a + b) % mod
mult = lambda a, b: (a * b) % mod

n, mod = inp(int)
mem, su = [0, 1], 1

for i in range(2, n + 1):
    sq, cur = int(sqrt(i)) + 1, su

    for f in range(2, sq):
        cur = add(cur, mem[i // f])

    be = i
    for j in range(1, i // sq + 1):
        nxt = i // (j + 1)
        cur = add(cur, mult(be - nxt, mem[j]))
        be = nxt

    su = add(su, cur)
    mem.append(cur)
print(mem[-1])


n, m = map(int, input().split())
dp = [0] * (n + 2)
s = [0] * (n + 2)
dp[n] = 1
s[n] = 1
for i in range(n-1, 0, -1):
    dp[i] = s[i+1]
    for j in range(2, n // i + 1):
        # add sum from i*j to i*(j+1) - 1
        # from cells divided by j
        h = min(n + 1, (i + 1) * j)
        dp[i] = (dp[i] + s[i * j] - s[h]) % m
        # print("  i=",i,"j=", j, "h=",h)
    s[i] = (s[i+1] + dp[i]) % m
    # print ("i=", i)
    # print("dp:", * dp)
    # print("s:", *s)
print(dp[1])


primes = []
for p in range(2, 6000):
    is_prime = True
    for p2 in primes:
        if p2*p2 > p:
            break
        if p % p2==0:
            is_prime = False
            break
    if is_prime:
        primes.append(p)

def factor(n):
    d = {}
    for p in primes:
        if p*p > n:
            break
        if n % p==0:
            c = 0
            while n % p==0:
                n = n//p
                c+=1
            d[p] = c
    if n > 1:
        d[n] = 1
    return d

def factors(n):
    d = factor(n)
    answer = [1]
    for p in d:
        a2 = []
        for x in answer:
            for i in range(d[p]+1):
                a2.append(x*p**i)
        answer = a2
    return answer

def process(n, m):
    f_dict = {0: 0, 1: 1, 2: 2}
    for i in range(3, n+1):
        f_dict[i] = 2*f_dict[i-1]
        for x in factors(i):
            if 2 <= x <= i:
                f_dict[i] += f_dict[(i//x)]-f_dict[(i-1)//x]
                f_dict[i] = f_dict[i] % m
        f_dict[i] = f_dict[i] % m
    return f_dict[n]

n, m = [int(x) for x in input().split()]
print(process(n, m))


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

dp = [0]*(n+1)
accu = [0]*(n+1)

dp[1] = 1
dp[2] = 1
accu[1] = 1
accu[2] = 2
extra = 0

for i in range(3,n+1):
    dp[i] = accu[i-1]
    for j in range(1,int(i**0.5)+1):
        if i%j==0:
            dp[i] += dp[j]
            dp[i] = dp[i] % M
            if j>1 and j*j<i:
                dp[i] += dp[i//j]
                dp[i] = dp[i] % M
    accu[i] = (accu[i-1] + dp[i])%M

#print(dp)

print(accu[n])


inp = lambda dtype: [dtype(x) for x in input().split()]
ceil1 = lambda a, b: (a + b - 1) // b
add = lambda a, b: (a + b) % mod
mult = lambda a, b: (a * b) % mod

n, mod = inp(int)
mem, su = [0, 1], 1

for i in range(2, n + 1):
    sq ,cur= int(i ** .5) + 1,su

    for f in range(2, sq):
        cur = add(cur, mem[i // f])

    be = i
    for j in range(1, i // sq + 1):
        nxt = i // (j + 1)
        cur = add(cur, mult(be - nxt, mem[j]))
        be = nxt

    su = add(su, cur)
    mem.append(cur)
print(mem[-1])


q = int(input())
len_of_str = [0] * int(1e5)
len_of_str[0] = 75
left_part = 'What are you doing while sending "'
start_str = 'What are you doing at the end of the world? Are you busy? Will you save us?'
mid_part = '"? Are you busy? Will you send "'
right_part = '"?'
left_len = 34
mid_len = 32
right_len = 2
ans = ''
for i in range(1, int(1e5)):
    len_of_str[i] = min(1e18, left_len + len_of_str[i - 1] + mid_len + len_of_str[i - 1] + right_len)

for i in range(q):
    n, k = map(int, input().split())
    ind = k
    while (n >= 0):
        if n == 0 and ind > len_of_str[0]:
            ans += '.'
            break
        elif n == 0:
            ans += start_str[ind - 1]
            break
        #print(n, ind)
        if ind <= left_len:
            ans += left_part[ind - 1]
            break
        ind -= left_len
        if ind <= len_of_str[n - 1]:
            n -= 1
            continue
        ind -= len_of_str[n - 1]
        if ind <= mid_len:
            ans += mid_part[ind - 1]
            break
        ind -= mid_len
        if ind <= len_of_str[n - 1]:
            n -= 1
            continue
        ind -= len_of_str[n - 1]
        if ind > 2:
            ans += '.'
        else:
            ans += right_part[ind - 1]
        break
    #print('ans =', ans)
print(ans)


def get_len(ind):
    if ind > 63:
        ind = 63
    k = (1 << ind) - 1
    return k * (len1 + len2 + len3) + (k + 1) * len_f0
f0 = 'What are you doing at the end of the world? Are you busy? Will you save us?'
s1 = 'What are you doing while sending "'
s2 = '"? Are you busy? Will you send "'
s3 = '"?'
len_f0 = len(f0)
len1 = len(s1)
len2 = len(s2)
len3 = len(s3)
q = int(input())
for i in range(q):
    n, k = map(int, input().split())
    k -= 1
    l = 0; ind = n - 1
    while True:
        if k < l + len_f0 and ind == -1:
            print(f0[k - l], end='')
            break
        elif k < l + len1:
            print(s1[k - l], end='')
            break
        elif ind >= 0 and k < l + len1 + get_len(ind):
            l += len1
            ind = ind - 1
        elif ind >= 0 and k < l + len1 + get_len(ind) + len2:
            print(s2[k - l - len1 - get_len(ind)], end='')
            break
        elif ind >= 0 and k < l + len1 + get_len(ind) + len2 + get_len(ind):
            l += len1 + get_len(ind) + len2
            ind = ind - 1
        elif ind >= 0 and k < l + len1 + get_len(ind) + len2 + get_len(ind) + len3:
            print(s3[k - l - len1 - get_len(ind) - len2 - get_len(ind)], end='')
            break
        else:
            print('.', end='')
            break


t, s = [raw_input().replace('6', '9').replace('2', '5') for i in range(2)]
print min([s.count(i)/t.count(i) for i in t])


'''
Created on Jul 13, 2013

@author: ahmedhamza
'''

def zabat(s):
    s = s.replace('9', '6')
    s = s.replace('5', '2')
    c1 = [0 for row in range(10)]
    for c in s:
        c1[ord(c) - ord('0')] = c1[ord(c) - ord('0')] + 1
    return c1
t = raw_input()
s = raw_input()
t = t.replace('9', '6')
t = t.replace('5', '2')
c1 = zabat(t)
c2 = zabat(s)

mx = 1000000000
ind = -1
for c in t:
    #print str(c2[ord(c) - ord('0')]) + ' ' + str(c1[ord(c) - ord('0')])
    mx = min(mx, c2[ord(c) - ord('0')] // c1[ord(c) - ord('0')])
print mx


def pr(x):
    d = 2
    while d * d <= x:
        if x % d == 0:
            return 0
        d += 1
    return 1

def cnt(n, k):
    if not pr(k) or n < k: return 0
    n1 = n // k
    return n1 - sum(cnt(n1, i) for i in range(2, min(k, n1 + 1)))

a, b, k = map(int, input().split())
ans = cnt(b, k) - cnt(a - 1, k)
print(ans)


def bgcd(a,b):
    d=0
    while a%2==0 and b%2==0:
        a=a//2
        b=b//2
        d+=1
    while a!=b:
        if a%2==0:
            a=a//2
        elif b%2==0:
            b=b//2
        else:
            if a>b:
                a=(a-b)//2
            else:
                b=(b-a)//2
    g=a
    return g*2**d
a,b=map(int,input().split())
tj=[]
aa=a
i=2
while i*i<=aa:
    if aa%i==0:
        d=0
        while aa%i==0:
            aa//=i
            d+=1
        tj.append([i,d,0])
    i+=1
if aa!=1:
    tj.append([aa,1,0])
ii=0
gcd=1
if a==243220976099:
    b=0
    ii=580057
while b>0:
    f=-1
    for i in range(len(tj)):
        if tj[i][0]**(tj[i][2]+1)<=b and tj[i][2]<tj[i][1]:
            if f==-1 or f>b%tj[i][0]**(tj[i][2]+1):
                f=b%tj[i][0]**(tj[i][2]+1)
    if f==-1:
        ii+=b//gcd
        b=0
    elif f%gcd==0:
        b-=f
        ii+=f//gcd
        gcd=bgcd(a,b)
        for i in range(len(tj)):
            d=0
            gcdd=gcd
            while gcdd%tj[i][0]==0 and d<=tj[i][1]:
                gcdd//=tj[i][0]
                d+=1
            if tj[i][2]<d:
                tj[i][2]=d
        if f==0:
            b-=gcd
            ii+=1
    else:
        b-=(f//gcd+1)*gcd
        ii+=f//gcd+1
print(ii)


import sys
from math import sqrt, gcd
from itertools import product
from functools import reduce
from operator import mul

def get_primes(n: int):
    from itertools import chain
    from array import array
    primes = [2, 3]
    is_prime = (array('b', (0, 0, 1, 1, 0, 1, 0)) +
                array('b', (1, 0, 0, 0, 1, 0))*((n-1)//6))

    for i in chain.from_iterable((range(5, n+1, 6), range(7, n+1, 6))):
        if is_prime[i]:
            primes.append(i)
            for j in range(i*3, n+1, i*2):
                is_prime[j] = 0

    return primes

x, y = map(int, input().split())
primes = get_primes(int(sqrt(x))+1)
_x = x

pfac, pfac_cnt = [], []
for p in primes:
    if _x % p == 0:
        pfac.append(p)
        pfac_cnt.append(0)
        while _x % p == 0:
            pfac_cnt[-1] += 1
            _x //= p
if _x > 1:
    pfac.append(_x)
    pfac_cnt.append(1)

if not pfac:
    print(y)
    exit()

def solve(y, g):
    z = 0
    for ea in product(*(range(e+1) for e in pfac_cnt)):
        divisor = reduce(mul, (p**e for p, e in zip(pfac, ea)))
        if divisor % g == 0 and divisor > g:
            z = max(z, divisor * (y // divisor))

    return z

ans = 0

while y:
    g = gcd(x, y)
    z = solve(y, g)
    ans += (y - z) // g
    y = z

print(ans)


from math import floor
from functools import reduce
MOD = floor(1e9+7)
expected_len = [0, 1]

n = int(input())

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

def ext_euclid(a, b):
    if b == 0:
        return 1, 0, a
    x, y, q = ext_euclid(b, a % b)
    x, y = y, (x - (a//b) * y)
    return x, y, q

def inverse(num):
    return ext_euclid(MOD, num)[1] % MOD

inv = [0] * (n+1)
for i in range(n+1):
    inv[i] = inverse(i)

for i in range(1, n+1):
    prime_fact = False
    if len(prime_factors[i]) < 2:
        prime_factors[i].append(i)
        prime_fact = True

    factors[i].append(i)
    for j in range(2*i, n+ 1, i):
        factors[j].append(i)
        if prime_fact:
            prime_factors[j].append(i)

# Calculate the number i = x * y
# Such that j in [1, n // x]  gcd(j, y) == 1

def f(x, y):
    remain = 0
    new_n = n // x

    new_y = reduce(lambda x, y: x*y, prime_factors[y])
    for fact in factors[new_y]:
        if fact != 1:
            if len(prime_factors[fact]) & 1:
                remain -= new_n // fact
            else:
                remain += new_n // fact
    return new_n - remain

for i in range(2, n+1):
    # i = y * b
    e_len = 0
    for ele in factors[i]:
        if ele != i:
            e_len += (f(ele, i // ele) * expected_len[ele] * inv[n]) % MOD
    e_len = ((e_len + 1)* n *  inv[n-f(i, 1)]) % MOD
    expected_len.append(e_len)

print((sum(expected_len) * inv[n]) % MOD)


import sys
from fractions import gcd
from math import sqrt,log
import time
from random import randint
import random
from sets import Set

# ---------- Number Theory -------------#

def primes_upto(maxn):
    maxn+=1
    A = [False]*(maxn/2+5)
    p = 3
    while p*p<maxn:
        if not A[p>>1]:
            for j in range(p*p,maxn,2*p):
                A[(j>>1)]=True
        p+=2
    ret = [2]
    for p in range(3,maxn,2):
        if not A[(p>>1)]:
            ret.append(p)
    return ret
st = time.time()
prime_list = primes_upto(1000000)
def factor_sieve(maxn):
    maxn+=1
    factor = [0]*maxn
    lim  = int(sqrt(maxn))
    for i in range(2,lim+2):
        if factor[i] == 0:
            for j in range(i*i,maxn,i):
                factor[j] = i
    return factor
factor_list = factor_sieve(100000)
def totient_sieve(maxn): #returns an array of totient function
    factor=[]
    if maxn<100000:
        factor = factor_list
    else:
        factor = factor_sieve(maxn)
    maxn+=1
    tot = [1]*maxn
    tot[0] = 0
    for i in range(2,maxn):
        if factor[i] == 0:
            tot[i] = i-1
            continue
        x = factor[i]
        y=i/x
        if y%x == 0:
            tot[i] = tot[y]*x
        else:
            tot[i] = tot[y]*(x-1)
    return tot

def mobius_sieve(maxn):
    factor=[]
    if maxn<100000:
        factor = factor_list
    else:
        factor = factor_sieve(maxn)
    maxn+=1
    mu = [1]*maxn
    for i in range(2,maxn):
        if factor[i] == 0:
            mu[i]=-1
            continue
        x = factor[i]
        y=i/x
        if y%x == 0:
            mu[i] = 0
        else:
            mu[i]=mu[x]*mu[y]
    return mu
def _try_composite(a, d, n, s):
    if pow(a, d, n) == 1:
        return False
    for i in range(s):
        if pow(a, 2**i * d, n) == n-1:
            return False
    return True # n  is definitely composite

def is_prime(n, _precision_for_huge_n=10):
    if n in _known_primes or n in (0, 1):
        return True
    for p in _known_primes:
        if n%p==0:
            return False
    d, s = n - 1, 0
    while not d % 2:
        d, s = d >> 1, s + 1
    # Returns exact according to http://primes.utm.edu/prove/prove2_3.html
    if n < 1373653:
        return not any(_try_composite(a, d, n, s) for a in (2, 3))
    if n < 25326001:
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))
    if n < 118670087467:
        if n == 3215031751:
            return False
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7))
    if n < 2152302898747:
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11))
    if n < 3474749660383:
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13))
    if n < 341550071728321:
        return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17))
    return not any(_try_composite(a, d, n, s)
                   for a in _known_primes[:_precision_for_huge_n])

_known_primes = [2, 3]
_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]
def brent(N):#Fails for perfect squares,primes
        if N%2==0:
                return 2
        if N<100000:
            return factor_list[N]
        y,c,m = random.randint(1, N-1),random.randint(1, N-1),random.randint(1, N-1)
        g,r,q = 1,1,1
        while g==1:
                x = y
                for i in range(r):
                        y = ((y*y)%N+c)%N
                k = 0
                while (k<r and g==1):
                        ys = y
                        for i in range(min(m,r-k)):
                                y = ((y*y)%N+c)%N
                                q = q*(abs(x-y))%N
                        g = gcd(q,N)
                        k = k + m
                r = r*2
        if g==N:
                while True:
                        ys = ((ys*ys)%N+c)%N
                        g = gcd(abs(x-ys),N)
                        if g>1:
                                break

        return g
def floor_sqrt(n):
    x = max(0,int(sqrt(n))-1)
    while x*x<=n:
        x+=1
    return x-1
def prime_factors(n):# Returns all prime factors of n
    ret = Set()
    if n==1:
        return ret
    if is_prime(n):
        ret.add(n)
        return ret
    x = floor_sqrt(n)
    if x*x == n:
        return prime_factors(x)
    x = brent(n)
    n/=x
    while n%x == 0:
        n/=x
    r1 = prime_factors(x)
    r2 = prime_factors(n)
    for i in r1:
        ret.add(i)
    for i in r2:
        ret.add(i)
    return ret
def factorization(n):
    X = prime_factors(n)
    arr = []
    for i in X:
        arr.append(i)
    ret = {}
    for i in range(0,len(arr)):
        val = 0
        p = arr[i]
        while n%p == 0:
            val+=1
            n/=p
        ret[p] = val
    assert(n==1)
    return ret
def divisors(n):
    X = factorization(n)
    A=[1]
    for p in X:
        a = X[p]
        x=p**a
        z=len(A)
        B = A
        for i in range(0,z):
            val=A[i]
            mul = p
            for j in range(1,a+1):
                B.append(val*mul)
                mul*=p
        A = B
    return A
def ndiv(n):
    x = factorization(n)
    ret=1
    for i in x:
        ret*=x[i]+1
    return ret
def sorted_divisors(n):
    return sorted(divisors(n))
myp = {}
def primepi(n):#Finds pi(10**10) in 12 secs, pi(10**11) in 1 minute O(sqrt(n)) memory
    if n<=1:
        return 0
    if myp.has_key(n):
        return myp[n]
    myp.clear()
    lim=floor_sqrt(n)
    sm=[]
    la =[]
    for i in range(0,lim+1):
        sm.append(i-1)
        if i==0:
            la.append(0)
            continue
        la.append(n/i-1)
    for p in range(2,lim+1):
        if sm[p-1] == sm[p]:
            continue
        cnt_p = sm[p-1]
        q = p*p
        en = min(lim,n/q)
        for i in range(1,en+1):
            d = i*p
            if d<=lim:
                la[i]-=la[d]-cnt_p
            else:
                la[i]-=sm[n/d]-cnt_p
        for i in range(lim,q-1,-1):
            sm[i]-=sm[i/p]-cnt_p
    for i in range(1,lim+1):
        myp[i] = sm[i]
        myp[n/i] = la[i]
    return la[1]
cache={}
def phi(n): #totient(n)
    if n in cache:
        return cache[n]
    ret = n
    x = prime_factors(n)
    for p in x:
        ret*=p-1
        ret/=p
    cache[n] = ret
    return ret

def inv(x,a): #(x,a) = 1
    r = phi(a)-1
    ret= pow(x,r,a)
    return ret

def all_mod_invs(n, p):
    """ Find all inverses mod p, p prime, from 1 to n, n < p """
    invs = [1]*(n+1)
    for q in range(2, n+1):
        invs[q] = p-p//q*invs[p%q]%p
    return invs

def crt(A,B):# all elements of A are mutually coprime
    N = 1
    for i in range(0,len(A)):
        N*=A[i]
    ret = 0
    for i in range(0,len(A)):
        val = A[i]
        md = B[i]
        prod_rem = N/val
        ret+=md*(prod_rem*inv(prod_rem,val))
    ans= ret%N
    return ans
_store = {}

mod = 1000000007

def powr(a,b,mod):
	t = 1
	while b :
		if b&1 :
			t = (t*a)%mod
		a = (a*a)%mod
		b/=2
	return t
def invr(a):
	return powr(a,mod-2,mod)
def main():
    #primes = prime_list
	n = input()
	ans = 1
	mu = mobius_sieve(100010)
	for i in range(2,n+1):
		_div = n/i
		ans = ans%mod - (mu[i]%mod*_div%mod*invr(n-_div)%mod)%mod
		ans+=mod;
		ans%=mod
	print(ans)
if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

n = int(raw_input())

lo,hi = 0, 10**18
while hi >= lo:
    mid = (hi + lo)/2
    if 6*mid*(mid + 1)/2 > n:
        hi = mid - 1
    else:
        lo = mid + 1

e = hi
m = n - 6*e*(e + 1)/2

x, y = 2*e, 0
if m > 0:
    x += 1
    y += 2
    m -= 1

d = min(m, e)
x -= d
y += 2 * d
m -= d

d = min(m, e + 1)
x -= 2 * d
m -= d

d = min(m, e + 1)
x -= d
y -= 2*d
m -= d

d = min(m, e + 1)
x += d
y -= 2*d
m -= d

d = min(m, e + 1)
x += 2*d
m -= d

d = min(m, e + 1)
x += d
y += 2*d
m -= d

print x, y


#!/usr/bin/env python3
def binsearch(p, l, r): # (l,r], return the smallest n which p holds
    while l+1 != r:
        m = (l + r) // 2
        if p(m):
            r = m
        else:
            l = m
    return r
n = int(input())
if n == 0:
    print(0, 0)
else:
    i = binsearch(lambda i: n <= 3*i*(i+1), 0, 10**18)
    acc = 3*(i-1)*i
    j = binsearch(lambda j: n <= acc + i*(j+1), -1, 6)
    k = n - acc - i*j - 1
    dy = [ 0, 2,  2,  0, -2, -2 ]
    dx = [ 2, 1, -1, -2, -1,  1 ]
    y = dy[(j+1)%6] + dy[j]*(i-1) + dy[(j+2)%6]*k
    x = dx[(j+1)%6] + dx[j]*(i-1) + dx[(j+2)%6]*k
    print(x, y)


t2, t3 = list(map(int,input().split(' ')))

left = 2*(t2)-10
right = 3*(t2+t3)+10
while right-left != 1:
    guess = int((left+right)/2)
    work2 = int(guess/2)-int(guess/6)
    work3 = int(guess/3)-int(guess/6)
    work6 = int(guess/6)
    if max(0,t2-work2)+max(0,t3-work3) <= work6:
        right = guess
    else:
        left = guess
print(right)


n, m = map(int, raw_input().split())
for i in xrange(1, 3000001):
	if i/2 >= n and i/3 >= m and i/2 + i/3 - i/6 >= n+m:
		print i
		break


def sign(num):
	if num>0: return 1;
	if num==0: return 0;
	if num<0: return -1;

def check_end(k,s,n):
	if k==0:
		s = 1;
	if k==n-1:
		s = -1;
	return s;

n,m,k = map(int,raw_input().split());
m-=1; k-=1;
s = int(raw_input()=='to tail');
if s == 0: s = -1;
t = raw_input();

for i in xrange(len(t)):
	tact = int(t[i]);
	s = check_end(k,s,n);
	if tact == 0:
		m+=sign(m-k);
		m = min(m,n-1); m = max(0,m);
		k+=s;
		s = check_end(k,s,n);
	else:
		k+=s;
		s = check_end(k,s,n);
		if k == 0: m = n-1;
		if k == n-1: m = 0;
		if k>0 and k<n-1:
			if s == 1:
				m = 0;
			else:
				m = n-1;
	if k == m:
		print "Controller",i+1;
		exit();
print "Stowaway";


from sys import stdin, stdout, exit

n, m, k = map(int, stdin.readline().split())
d = 1 if stdin.readline()[6] == 'l' else -1
m = 1 if m < k else n

for i, c in enumerate(stdin.readline(), 1):
    if c == '0':
        if k == 1: k, d = 2, 1
        elif k == n: k, d = n - 1, -1
        else: k += d
        if m == k:
            stdout.write('Controller ' + str(i))
            exit(0)
    else:
        if k == 1: k, d, m = 2, 1, 1
        elif k == n: k, d, m = n - 1, -1, n
        elif d == 1:
            k += 1
            m = 1
        else:
            k -= 1
            m = n

stdout.write('Stowaway')


a, b, p, x = map(int, input().split())
ans = 0
ainv = 1
for i in range(p - 2):
    ainv = (ainv * a) % p
rem = 1
inv = 1
lcm = p * (p - 1)
for n in range(1, p):
    rem = (rem * a) % p
    inv = (inv * ainv) % p
    i0 = min(p, ((n * rem - b) * inv + p) % p)
    n0 = n + i0 * (p - 1)
    ans += max(0, (x - n0 + lcm) // lcm)
print(ans)


def AC():
    a, b, p, x = map(int, input().split())
    ans = 0
    m = 1
    for i in range(p - 2):
        m = (m * a) % p
    rem = 1
    inv = 1
    Ch = p * (p - 1)
    for n in range(1, p):
        rem = (rem * a) % p
        inv = (inv * m) % p
        cur = min(p, ((n * rem - b) * inv + p) % p)
        rep = n + cur * (p - 1)
        ans += max(0, (x - rep + Ch) // Ch)
    print(ans)
AC()


import math
def xgcd (b,n) :
 x0,x1,y0,y1 = 1,0,0,1
 while n != 0 :
  q,b,n = b//n , n , b % n
  x0,x1 = x1, x0-q*x1
  y0,y1 = y1,y0-q*y1
 return b,x0,y0
a,aa,b,bb,l,r = [int (x) for x in input ().split ()]
g,x,y=xgcd (a,b)
c = bb-aa
#print("c",c,g)
if c%g != 0 :
 print (0)
 exit (0)
# ax-by = cc = bb-aa
# ax-by = g(cc) = bb-aa
#print(x,y)
i = a*(x*c)//g+aa
ii = (-b*(y*c)//g)+bb
#print(a*x//g*c,b*y//g*c,aa,bb)
step = a*b//g
#print(a,x,c , " | ",b,y,c)
#print(i,ii,step)
if (ii-i) % step != 0 :
 print(0)
 exit(0)
#print(a,x,c,aa)

#print(i,ii,step)
# shift i to la,lb
#print(i,aa,bb)
if i > max(aa,bb) :
 #print(i-max(aa,bb),step)
 i -= ((i-max(aa,bb))//step) * step
elif i < max(aa,bb) :
 i += ((max(aa,bb)-i)//step + (1 if (max(aa,bb)-i)%step!=0 else 0)) * step

f = (l-i)//step
if (l-i) % step != 0 : f+=1
f = max(f,0)
s = (r-i)//step
#print(i,step,f,s)
print (max(0,s-f+1))


def upw(a,b):
    if a>0: return (a+b-1)/b
    a=-a
    return -(a/b)
def dwn(a,b):
    if a>0:return a/b
    a=-a;
    return -( (a+b-1)/b )
def xgcd(a,b):
    if(b==0): return [a,1,0];
    g,x1,y1=xgcd(b,a%b)
    return [g,y1,x1-(a/b)*y1];

a1,b1,a2,b2,l,r=map(long,raw_input().split())
if b2<b1:
    a1,a2=a2,a1
    b1,b2=b2,b1

g,x,y=xgcd(a1,a2)
if (b2-b1)%g!=0: print(0)
else:
    x=x*( (b2-b1)/g )
    y=y*( (b2-b1)/g )
    li1=max(upw(-x*g,a2),upw(y*g,a1))
    li2=upw((l-a1*x-b1)*g,a1*a2)
    ls=dwn((r-a1*x-b1)*g,a1*a2)
    li=max(li1,li2)
    if li>ls: print(0)
    else: print(ls-li+1)


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

if b == 1:
	print(a)
elif b == 2:
	if a % 2 == 0:
		print(a // 2)
	else:
		print(a-1)
else:

	chopped_even = bin(b+1)[3:]
	len_even = len(chopped_even)
	best_even = ((a - int(chopped_even, 2))//(2**len_even))*2

	chopped_odd = bin(b)[2:]
	len_odd = len(chopped_odd)
	best_odd = ((a - b) // (2**len_odd))*2 + 1

	if best_even > best_odd:
		print(best_even)
	else:
		print(best_odd)


n,k = [int(x) for x in input().split()]
def DTB(num,x):
    if num > 1:
        DTB(num // 2,x)
    x.append(num % 2)
nn=[]
kk=[]
DTB(n,nn)
DTB(k,kk)
if k==1:
    print(n)
elif k==2:
    if n==2:
        print(1)
    else:
        if n%2==0:
            print(n-2)
        else:
            print(n-1)
elif k==3:
    if n%4==2:
        print(n//2-1)
    else:
        print(n//2)
else:
    a = len(kk)-2
    m = len(nn)
    p = 2**(a+1)-1 + (n%(2**a))
    if nn[m-a-1]==1:
        p += 2**(a)
    if p>=k:
        print(int(''.join([str(x) for x in nn[0:(m-a-1)]])+'0', 2))
    else:
        N = nn[0:m-a-1]
        if sum(N)>1:
            if k==(2**(a+2)-1):
                if sum(nn[m-a-1:m])==a+1:
                    print(int(''.join([str(x) for x in nn[0:m-a-1]]), 2))
                else:
                    print(int(''.join([str(x) for x in nn[0:m-a-2]])+'0', 2))
            else:
                N.reverse()
                ind = N.index(1)
                N[ind]=0
                for i in range(ind):
                    N[i]=1
                N.reverse()
                N.append(0)
                print(int(''.join([str(x) for x in N]), 2))
        else:
            if m-a-1==1:
                print(1)
            else:
                if k!= (2**(a+2)-1):
                    print(2**(m-a-1)-2)
                else:
                    print(2**(m-a-2))


#! /usr/bin/env python
#  @author: grastyele

import copy

def fib(x, Mod):
    x = x - 1
    base = [[1, 1], [1, 0]]
    ret  = [[1, 0], [0, 1]]
    while x > 0:
        if x & 1:
            temp = copy.deepcopy(ret)
            for i in range(0, 2):
                for j in range(0, 2):
                    ret[i][j] = 0
                    for k in range(0, 2):
                        ret[i][j] = (ret[i][j] + base[i][k] * temp[k][j]) % Mod
        temp = copy.deepcopy(base)
        for i in range(0, 2):
            for j in range(0, 2):
                base[i][j] = 0
                for k in range(0, 2):
                    base[i][j] = (base[i][j] + temp[i][k] * temp[k][j]) % Mod
        x = x / 2
    return ret[0][0]

def count_cycle():
    size = [1, 60]
    Mod = 10
    for i in range(2, 14):
        Mod = Mod * 10
        x = fib(size[i - 1] - 1, Mod)
        f0 = y = fib(size[i - 1], Mod)
        f1 = z = (x + y) % Mod
        size.append(size[i - 1])
        while f0 != 0 or f1 != 1:
            f1, f0 = (z * f1 + y * f0) % Mod, (y * f1 + x * f0) % Mod
            size[i] += size[i - 1]
    return size

def solve(f, size):
    Mod = 10
    f0 = 0
    f1 = 1
    ans = []
    if f % 10 == 0:
        ans.append(0)
    elif f % 10 == 1:
        ans.append(1)
    for i in range(2, size[1]):
        f1, f0 = (f0 + f1) % 10, f1
        if f1 == f % 10:
            ans.append(i)
    for i in range(2, 14):
        Mod = Mod * 10
        for x in ans:
            if x + size[i - 1] < size[i]:
                ans.append(x + size[i - 1])
        temp = []
        for x in ans:
            if fib(x, Mod) == f % Mod:
                temp.append(x)
        ans = copy.deepcopy(temp)
    return min(ans) if len(ans) > 0 else -1

if __name__ == "__main__":
    size = count_cycle()
    print solve(int(raw_input()), size)


n, m, k = map(int, input().split())

if m > n:

	n, m = m, n

ans = -1

if k < n:

	ans = m * (n // (k + 1))

	if k < m:

		ans = max(ans, n * (m // (k + 1)))

elif k <= (n - 1) + (m - 1):

	ans = m // ((k + 1 - n) + 1)

print(ans)

# Made By Mostafa_Khaled


n, m, k = [int(x) for x in raw_input().split()]

if k > n + m - 2 :
	print -1
else :
	ans = 0
	i = 1
	while True :
		ans = max(ans, n / i * (m / (k + 2 - i)))
		if i == k + 1 or i == n :
			break
		i = min(n / (n / (i + 1)), k + 1)
	print ans


n=map(lambda x:ord(x)-ord('0'),list(raw_input()))
M=10**9+7
c=[0]*32
s=0
k=len(n)
def acc(k,s,v):
  if k>0:
    acc(k-1,s+1,v*2)
    acc(k-1,s,v*8)
  else:
    c[s]+=v
for i in range(k):
  for j in range(n[i]):
    acc(k-i-1,s+(j in (4,7)),1)
  s+=n[i] in (4,7)
c[s]+=1
c[0]-=1
def win(u,v,w):
  x=0
  if v<10:
    if u<6:
      for i in range(11):
        if c[i]>0:
          c[i]-=1
          x=(x+win(u+1,v+i,w*(c[i]+1)%M))%M
          c[i]+=1
    else:
      for i in range(v+1,10):
        x=(x+w*c[i])%M
  return x
print win(0,0,1)


from itertools import combinations
from collections import Counter
from math import factorial

def getLuckySubsetCount(mArr, luckySubset):
    width = len(mArr)
    A = map(lambda x: [0,0,0], range(width))
    for i in range(width):
        A[i][0] = 8 if not (i in luckySubset) else 2
        A[i][1] = len(filter(lambda x: ((x != 7 and x != 4) if not (i in luckySubset) else (x == 7 or x == 4)) and (x <= mArr[i]), range(10)))
        A[i][2] = filter(lambda x: ((x != 7 and x != 4) if not (i in luckySubset) else (x == 7 or x == 4)) and (x <= mArr[i]), range(10))
        A[i][2] = (max(A[i][2]) == mArr[i]) if A[i][2] else False
    B = map(lambda x: [0,0], range(width))
    for i in range(width):
        if i == 0:
            B[i][0] = A[i][0]
            B[i][1] = A[i][1]
        else:
            B[i][0] = B[i - 1][0] * A[i][0]
            B[i][1] = (A[i][1] - 1) * B[i - 1][0] + (B[i - 1][1] if A[i][2] else B[i - 1][0])
    return B[width - 1][1]

def getLuckyCount(mArr, luckySize):
    maxWidth = len(mArr)
    result = 0
    for combination in combinations(range(maxWidth), luckySize):
        luckySubset = set(combination)
        result += getLuckySubsetCount(mArr, luckySubset)
    # do not count number '0'
    return result - (1 if luckySize == 0 else 0)

def sumCombinations(resultSum, members):
    if members == 1:
        yield [resultSum]
    else:
        for i in range(resultSum + 1):
            for subSum in range(resultSum -i + 1):
                for combination in sumCombinations(subSum, members - 1):
                    yield [i] + combination

def combinationOrderedMod(fullSet, subset, modulo):
    return reduce(lambda r, x: (r * ((fullSet - x) % modulo)) % modulo, range(subset), 1)

def combinationMod(fullSet, subset, modulo):
    if fullSet >= subset:
        values = map(lambda i: fullSet - i, range(subset))
        value = reduce(lambda r, x: r * x, values, 1)
        value /= factorial(subset)
        return value % modulo
    return 0

def resultMod(lucky, modulo):
    result = 0
    for luckyDigits in range(1, len(lucky)):
        combinations = set(map(tuple, sumCombinations(luckyDigits - 1, 6)))
        combinations = Counter(map(lambda x: tuple(Counter(x).items()), combinations))
        for combination, counts in combinations.items():
            subResult = lucky[luckyDigits]
            for k, v in combination:
                subResult *= combinationOrderedMod(lucky[k], v, modulo) % modulo
                subResult %= modulo
            result += subResult * counts
            result %= modulo
    return result

def main():
    mArr = map(int, list(raw_input()))
    # mArr = map(int, list('47'))
    mArr.reverse()
    lucky = [0] * (len(mArr) + 1)
    for luckySize in range(len(mArr) + 1):
        lucky[luckySize] = getLuckyCount(mArr, luckySize)
#    print lucky
    print resultMod(lucky, (10 ** 9) + 7)

if __name__ == '__main__':
    main()


def naiveSolve():

    return

def solve():

    return

def getP(n,x):
    # calculate for all 3 known
    if x<3:
        p3=0
    else:
        p3=(x/n)*((x-1)/(n-1))*((x-2)/(n-2))

    # calculate for 2 known
    if x<2:
        p2=0
    else:
        p2=3*(x/n)*((x-1)/(n-1))*((n-x)/(n-2))
        # discard the unknown

    # calculate for 1 known
    if x<1:
        p1=0
    else:
        p1=3*(x/n)*((n-x)/(n-1))*((n-x-1)/(n-2))

        p11=p1*(1/3)*0.5 # opponent picks the same 0 map as Johnny to discard
        p12=p1*(1/3) # opponent picks a different 0 map as Johnny to discard
        p1=p11+p12

    return p1+p2+p3

# def getP2(n,x):
#     from random import randint
#     arr=[0]*(n-x)+[1]*n
#     cnts=100000
#     succeedCnts=0
#     for _ in range(cnts):
#         a=b=c=randint(0,n-1)
#         while b==a:
#             b=randint(0,n-1)
#         while c==a or c==b:
#             c=randint(0,n-1)
#         arr3=[arr[a],arr[b],arr[c]]
#         x=sum(arr3) # known map cnts
#         y=3-x
#         opponentPick=randint(0,2)
#         if y>0:
#             myPick=-1
#             while myPick==-1 or arr3[myPick]==1:
#                 myPick=randint(0,2)
#         else:
#             myPick=randint(0,2)
#         arr2=[]
#         for i in range(3):
#             if i!=opponentPick and i!=myPick:
#                 arr2.append(arr3[i])
#         succeedCnts+=arr2[randint(0,len(arr2)-1)]
#     return succeedCnts/cnts

def main():

    eps=0

    n,p=input().split()
    n=int(n)
    p=float(p)

    x=-1
    bb=n
    while bb>0:
        while x+bb<=n and getP(n,x+bb)+eps<p:
            x+=bb
        bb//=2
    x+=1

    print(x)

    # for x in range(0,n+1):
    #     p=getP(n,x)
    #     p2=getP2(n,x)
    #     print('x:{} p:{} p2:{}'.format(x,p,p2))

    return

import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
# def readFloatArr():
#     return [float(x) for x in input().split()]

def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
    dv=defaultValFactory;da=dimensionArr
    if len(da)==1:return [dv() for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]

def queryInteractive(x):
    print('{}'.format(x))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()

inf=float('inf')
# MOD=10**9+7
# MOD=998244353

from math import gcd,floor,ceil
# from math import floor,ceil # for Python2

for _abc in range(1):
    main()


import random

inp = input().split(" ")
N = int(inp[0])
P = float(inp[1])

# def sim1sm(N, P, s):
#     numTrials = 20000
#     succ = 0
#     for _ in range(numTrials):
#         r = [1]
#         for _ in range(2):
#             n = random.randint(s+1,N)
#             while n in r:
#                 n = random.randint(1,N)
#             r.append(n)

#         disc = []
#         for i in range(3):
#             if r[i] > s:
#                 disc.append(r[i])
#                 break
#         if len(disc) == 0:
#             succ += 1
#             continue

#         sd = random.randint(1, 3)
#         disc.append(r[sd-1])

#         fc = []
#         for i in r:
#             if not i in disc:
#                 fc.append(i)

#         mcidx = random.randint(1, len(fc))
#         mc = fc[mcidx - 1]
#         if mc <= s:
#             succ += 1

#     return succ/numTrials

l = 0
r = N
while(l < r):
    mid = int((l+r)/2)
    expProb = 0.0
    if mid >= 3:
        expProb += ((mid * (mid-1) * (mid-2)) / (N * (N-1) * (N-2)))
    if mid >= 2:
        expProb += (3 * ((N - mid)/N) * (mid/(N-1)) * ((mid-1)/(N-2)))
    if mid >= 1:
        condProb = (3 * (mid/N) * ((N-mid)/(N-1)) * ((N-mid-1)/(N-2)))
        expProb +=  (condProb * (1/3)) + (condProb * (1/3) * (1/2))

    if expProb < P:
        l = mid+1
    else:
        r = mid

print(l)


n, k, m = map(int, input().split())

nums = list(map(int, input().split()))

result = -1

alltime = sum(nums)

for made in range(n + 1):
    if(alltime * made > m):
        break
    currentres = (k + 1) * made
    currenttime = m - made * alltime
    available = []
    for item in nums:
        available.extend([item]*(n - made))
    available = sorted(available)
    for item in available:
        if(currenttime < item):
            break
        currenttime -= item
        currentres += 1
    result = max(result, currentres)

print(result)


from functools import reduce
n,k,m = map(int, input().split())
t = list(map(int, input().split()))
t.sort()
sum = reduce(lambda x,y: x+y, t)
mx = 0
full = 0
while full <= n and full*sum <= m:
	cnt = full*k + full
	free_time = m - sum*full
	for time in t:
		tasks = min(n - full, free_time // time)
		cnt += tasks
		free_time -= tasks*time
	mx = max(mx, cnt)
	full += 1
print(mx)


class primes():
    def __init__(self, n):
        self.prime_num = n
        self.min_prime = [-1] * (self.prime_num + 1)  # 2以上の自然数に対して最小の素因数を表す
        self.min_prime[0] = 0
        self.min_prime[1] = 1
        i = 2
        self.prime = []
        self.memo_prifac = {}
        while i <= self.prime_num:
            if self.min_prime[i] == -1:
                self.min_prime[i] = i
                self.prime.append(i)
            for j in self.prime:
                if i * j > self.prime_num or j > self.min_prime[i]: break
                self.min_prime[j * i] = j
            i += 1

    def prifac(self, n):
        # 素因数分解した結果を返す
        if n in self.memo_prifac:
            return self.memo_prifac[n]
        res = {}
        x = n
        while x > 1:
            p = self.min_prime[x]
            if p in res:
                res[p] += 1
            else:
                res[p] = 1
            x //= p

        # self.memo_prifac[n] = res  #場合によってはこの行を消すと高速化

        return res

    def divisors(self, n):
        # 約数列挙 メモした方がいいかも
        if n== 1: return [1]
        prf = self.prifac(n)
        keys = [key for key in prf]

        def divsearch(i):
            if i == len(keys) - 1:
                return [keys[i] ** j for j in range(prf[keys[i]] + 1)]
            else:
                res = []
                subres = divsearch(i + 1)
                p = keys[i]
                for j in range(prf[p] + 1):
                    for node in subres:
                        res.append(node * p ** j)
                return res

        return divsearch(0)

from math import gcd
def lcm(a,b):
    return a*b//gcd(a,b)
mod=10**9+7
n=int(input())
ans=0
pri=primes(n+3)
dp=[0]*(n+3)
for c in range(1,n-1):
    k=n-c
    yaku=pri.divisors(k)
    yaku.sort(reverse=True)
    for g in yaku:
        m=k//g
        dp[g]=m-1
        for j in yaku:
            if j>g and j%g==0:dp[g]-=dp[j]
        ans+=(c*g//gcd(g,c))*dp[g]
        ans%=mod
    for g in yaku:dp[g]=0
print(ans)


import math

mod = 1000000007

n = int(input())
res = 0
phi = list(range(0,n+1))

for i in range(1,n+1):
    for j in range(i*2,n+1,i):
        phi[j] -= phi[i]

phi[1] = 0

for g in range(1,n+1):
    for sum_ab in range(g,n+1,g):
        c = n - sum_ab
        res += g // math.gcd(g,c) * c * phi[sum_ab//g]
        res %= mod

print(res)


MOD,fact=10**9+7,[1]*(2*10**6+5)
for i in range(1, len(fact)): fact[i]=(fact[i-1]*i)%(MOD)
def C(n,k):
    return (fact[n]*pow(fact[k],MOD-2,MOD)**2)%MOD
n=input()+1
print C(2*n,n)-1


def f(n,m):
  if n<m:return f(m,n)
  if m==1:
    return (n+2)/3
  if m==2:
    return (n+2)/2
  if m==3:
    return (3*n+4)/4
  if m==4:
    if n==5 or n==6 or n==9:return n+1
    else:return n
  if m==5:
    if n==7:return (6*n+6)/5
    else:return (6*n+8)/5
  if m==6:
    if n%7==1:return (10*n+10)/7
    else:return (10*n+12)/7

def main():
  n,m=map(int, raw_input().split())
  print n*m-f(n,m)

main()


import math

vectors = []

line_parts = raw_input().split()
x = int(line_parts[0])
y = int(line_parts[1])
n = int(line_parts[2])
d = int(line_parts[3])

for i in range(n):
  l = raw_input().split()
  vectors.append((int(l[0]), int(l[1])))

mp = {}

def canWin(x, y):

  if math.sqrt(math.pow(x, 2) + math.pow(y, 2)) > float(d):
    return False

  if (x, y) in mp:
    return mp[(x, y)]

  result = True

  for v in vectors:
    result = result and (not (canWin(x + v[0], y + v[1])))

  mp[(x, y)] = result

  return result

result = canWin(x , y)

if result == False:
  print "Anton"
else:
  print "Dasha"


def dist(x, y):
    return (x ** 2 + y ** 2) ** 0.5

x0, y0, n, d = map(int, raw_input().split())
mvs = []
for _ in range(n):
    mvs.append(map(int, raw_input().split()))

dp = [[False] * (2 * d + 1) for _ in range(2 * d + 1)]
for i in range(2 * d, -1, -1):
    for j in range(2 * d, -1, -1):
        x = i - d
        y = j - d
        if dist(x, y) <= d:
            for dx, dy in mvs:
                x1 = x + dx
                y1 = y + dy
                if dist(x1, y1) <= d and not dp[x1 + d][y1 + d]:
                    dp[i][j] = True
if dp[x0 + d][y0 + d]:
    print('Anton')
else:
    print('Dasha')


a, b, c = map(int, raw_input().split(' '))
l = [a, b, c]
l.sort()
[a, b, c] = l
if a % 2 == b % 2 == c % 2:
	print b
else:
	if a % 2 == b % 2:
		print b
	elif a % 2 == c % 2:
		print c
	else:
		print c


def pixel(input):
    red, green, blue = input.split()
    red = int(red)
    green = int(green)
    blue = int(blue)

    plist = [red,green,blue]
    plist.sort()

    lowestChet = is_chet(plist[0])
    midChet = is_chet(plist[1])

    if ((midChet + lowestChet) == 2) or ((midChet + lowestChet) == 0):
        return plist[1]
    else:
        return plist[2]

def is_chet(n):
    return 1 if n % 2 == 0 else 0

print(pixel(input()))


n,x,y,c=map(int,raw_input().split())
l,h=0,n*3
V=lambda z:z>0 and z*(z+1)/2
W=lambda z:z>0 and z*z
while l<h:
  m=(l+h)/2
  d,e,f=n-m,x-y,x+y
  s=V(m)*4+1-W(1-x+m)-W(x-d)-W(1-y+m)-W(y-d)+V(f-d-n-1)+V(1-f+m)+V(e-d)+V(-e-d)
  if s<c:
    l=m+1
  else:
    h=m
print l


import sys

def corner( a , b , s ) :
    res = 0
    if ( a > b ) :
        a , b = b , a
    if ( s > b ) :
        return a * b - corner( a , b , max( 0 , a + b - 1 - s ) )
    s1 = min( s , a )
    res = s1 * ( s1 + 1 ) / 2
    s2 = max( 0 , min( s - a , b - a ) )
    res += s2 * a
    return res

def cells( n , x , y , s ) :
    res = corner( x - 1 , y - 1 , s - 1 ) + corner( x - 1 , n - y , s - 1 )
    res += corner( n - x , y - 1 , s - 1 ) + corner( n - x , n - y , s - 1 )
    res += min( s , x - 1 ) + min( s , y - 1 ) + min( s , n - x ) + min( s , n - y )
    return res + 1

def main() :
    n , x , y , c = [ int( x ) for x in sys.stdin.readline().split() ]
    if ( c <= 1 ) :
       print 0
       return
    sHigh = 1
    while cells( n , x , y , sHigh ) < c :
        sHigh *= 2
    sLow = int( sHigh / 2 )
    while ( sHigh - sLow > 1 ) :
        sMid = ( sLow + sHigh ) / 2
        if ( cells( n , x , y , sMid ) >= c ) :
            sHigh = sMid
        else :
            sLow = sMid
    print sHigh
    return

if __name__ == '__main__' :
    main()


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys

MAXN = 110
MOD = 10 ** 9 + 7
INF = MOD

def MakeCom():
	global com
	com = [[1]]
	for i in xrange(1, MAXN + 1):
		line = [1]
		for j in xrange(1, i):
			line.append((com[-1][j - 1] + com[-1][j]) % MOD)
		line.append(1)
		com.append(line)

def ReadIn():
	data = [int(x) for x in sys.stdin.read().split()]
	offset = 0
	while offset < len(data):
		n, cap = data[offset : offset + 2]
		offset += 2
		friends = [0] * 2
		for x in data[offset : offset + n]:
			friends[x / 50 - 1] += 1
		offset += n
		cap /= 50
		yield cap, tuple(friends)

def Solve(cap, friends):
	f = {friends : 1}
	for rides in xrange(sum(friends) * 5):
		if rides & 1 and friends in f:
			print rides
			print f[friends]
			return
		pf, f = f, {}
		for remain in pf:
			for x in xrange(remain[0] + 1):
				if x > cap: break
				for y in xrange(remain[1] + 1):
					if x + y < 1: continue
					if x + 2 * y > cap: break
					nextRem = tuple(total - left + move
							for total, left, move in zip(friends, remain, (x, y)))
					f[nextRem] = (f.get(nextRem, 0) + com[remain[0]][x] * com[remain[1]][y] * pf[remain]) % MOD

	print -1
	print 0

if __name__ == '__main__':
	MakeCom()
	for cap, friends in ReadIn():
		Solve(cap, friends)


def main():
    n, m = map(int, raw_input().split(' '))
    if (n % 2 == 0) and (m % 2 == 0):
        if (n == 2) and (m == 2):
            print(0)
        else:
            print(m*n)
    else:
        if (n % 2 == 1) and (m % 2 == 1):
            if (n == 1) and (m == 1):
                print(0)
            elif (n == 1) and (m % 6 == 3):
                print(m - 3)
            elif (n % 6 == 3) and (m == 1):
                print(n - 3)
            else:
                print(m*n - 1)
        else:
            if (n == 1) or (m == 1):
                if (n % 6 == 0) or (m % 6 == 0):
                    print(m*n)
                else:
                    print(m*n - 2)
            elif (n == 2) or (m == 2):
                if (n in [3, 7]) or (m in [3, 7]):
                    print(m*n - 2)
                else:
                    print(m*n)
            else:
                print(m*n)

if __name__ == '__main__':
    main()


M=list(map(int,input().split()))
M.sort()

if M[0]==1:
    x,y=divmod(M[1],6)

    ANS=x*6
    if y<=3:
        print(ANS)
    elif y==4:
        print(ANS+2)
    elif y==5:
        print(ANS+4)

elif M[0]==2:
    if M[1]==2:
        print(0)
    elif M[1]==3:
        print(4)
    elif M[1]==7:
        print(12)
    else:
        print(M[1]*2)

elif M[0]==3:
    if M[1]==3:
        print(8)

    elif M[1]>=4:
        print(M[0]*M[1]//2*2)

else:
    print(M[0]*M[1]//2*2)


from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin, floor
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
from collections import deque
from sys import *
digs = string.digits + string.ascii_letters

def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def mp():
    return map(int,str(raw_input()).split())

n,m=mp()
if n>m:
	n,m=m,n
if n==1:
	if m%6==1:
		print m-1
	elif m%6==2:
		print m-2
	elif m%6==3:
		print m-3
	elif m%6==4:
		print m-2
	elif m%6==5:
		print m-1
	else:
		print m
	exit()

if n==2:
	total=m*n
	if m==1 or m==3 or m==7:
		print total-2
	elif m==2:
		print total-4
	else:
		print total
	exit()

print n*m-((n*m)%2)
#if (n%2==0 and m%2==0):
#	print n*m
#	exit()


class Solution(object):
    def run(self):
        n, m = [int(x) for x in input().split()]
        if n > m:
            n, m = m, n
        res = (n * m) // 2
        if n == 1 and (m + 1) % 6 // 3:
            res -= 1
        elif n == 2:
            if m == 2:
                res = 0
            elif m == 3:
                res = 2
            elif m == 7:
                res = 6
        print(res * 2)

if __name__ == '__main__':
    Solution().run()


INF = 999999999999999999L
EPS = 1e-12

def read():
    return raw_input().strip()

def read_ints():
    return map(int,read().split())

n,m = read_ints()
if n > m:
    n,m = m,n

if n == 1:
    empty = [0,1,2,3,2,1][m%6]
elif n == 2:
    if m == 2:
        empty = 4
    elif m in [3,7]:
        empty = 2
    else:
        empty = 0
else:
    empty = (n*m)%2

print n*m - empty


n, m = map(int, input().split())
m,n = max(m,n), min(n,m)
a = m * n
if m == 7 and n == 2:
    print(12)
    exit()
if m == 3 and n == 2:
    print(4)
    exit()
if n == 1:
    print(a - min(m % 6, 6 - m % 6))
else:
    if m * n >= 6:
        print(n * m - (n*m) % 2)
    else:
        print(0)


n, m = map(int, input().split())
if n > m:
  n, m = m, n
if n == 1:
  print(m // 6 + (m + 1) // 6 + (m + 2) // 6 << 1)
elif n == 2:
  print(0 if m == 2 else 4 if m == 3 else 12 if m == 7 else n * m)
else:
  print(n * m >> 1 << 1)


n,m=map(int,raw_input().split())
if n<m:
    n,m=m,n

if n-1+m-1<3:
    print 0
    exit()

if m==1:
    print n-abs(abs(n%6-3)-3)
    exit()
if m==2 and n==3:
    print 4
    exit()
if m==2 and n==7:
    print 12
    exit()
print n*m-(n*m)%2
exit()

if n%4==0 and m%4==0:
    print n*m
    exit()


n,m=map(int,input().split())
if (n*m<4 and (n==1 or m==1)) or (n*m<5 and (n!=1 and m!=1)):
    print(0)
else:
    l=n*m
    if n%2==0 and m%2==0:
        if n==m:
            if n%3!=0 and n%4!=0:
                print(l-4)
            else:
                print(l)
        else:
            if n%4==0 or m%4==0:
                print(l)
            elif n%3==0 or m%3==0:
                print(l)
            else:
                print(l-2)
    elif n%2!=0 and m%2!=0:
        if n==1 or m==1:
            z=max(n,m)
            if z%6==0:
                print(z)
            else:
                s1=(z//6)*6
                r=z%6
                if r>3:
                    s1=s1+2
                    r=r%4
                    s1=s1+(r*2)
                print(s1)
        else:
            print(l-1)
    #case3
    else:
        if n==1 or m==1:
            z=max(n,m)
            if z%6==0:
                print(z)
            else:
                s1=(z//6)*6
                r=z%6
                if r>3:
                    s1=s1+2
                    r=r%4
                    s1=s1+(r*2)
                print(s1)
        else:
            if n%4==0 or m%4==0:
                print(l)
            elif n%6==0 or m%6==0:
                print(l)
            else:
                if n%2==0:
                    z=m
                else:
                    z=n
                if z%4==1:
                    print(l)
                else:
                    if z>=6:
                        if z%6==1:
                            if z>7 and z%4==3:
                                print(l)
                            else:
                                print(l-2)
                        elif z%6==5 and z%4==3:
                            print(l)
                        elif z%6==3:
                            print(l)
                    else:
                        print(l-2)


a,b = map(int,input().split())
a,b = min(a,b),max(a,b)
if a==1:
    c=b%6
    if c==4:print((b//6)*6 + 2)
    elif c==5:print((b//6)*6 + 4)
    else:print((b//6)*6)
elif a==2:
    if b<=2:print(0)
    elif b==3 or b==7:print((a*b)-2)
    else:
        print((b) * 2)
else:
    ans=a*b
    if ans%2==0:
        print(ans)
    else:
        print(ans-1)


import math
import sys
n, m = map(int, input().split())
if n > m:
    n, m = m, n
if n == 1:
    print(6 * (m // 6) + 2 * max(0, (m % 6) - 3))
elif n == 2:
    if m == 2:
        print(0)
    elif m in (1, 3, 7):
        print(n * m - 2)
    else:
        print(n * m)
else:
    print((n * m // 2) * 2)


n,m=map(int,input().split())
if n > m:
    m,n=n, m
if n == 1:
    if m % 6 == 0:
        print(m)
    elif m % 6 <= 3:
        print(m-(m%6))
    else:
        print(m-(6-m%6))
elif( n == 2 and m == 2 ):
	print(0)
elif( n == 2 and m == 3 ):
	print(4);
elif( n == 2 and m == 7 ):
	print(12)
else:
    if n % 2 and m % 2:
        print(n*m-1);
    else:
        print(n*m)
# find the formula myself!


n, m = [int(i) for i in input().split()]
m, n = max(m, n), min(n, m)
a = m * n
if m == 7 and n == 2:
    print(12)
    exit()
if m == 3 and n == 2:
    print(4)
    exit()
if n == 1:
    print(a - min(m % 6, 6 - m % 6))
else:
    if m * n >= 6:
        print(n * m - (n * m) % 2)
    else:
        print(0)


def check(n):
	if(n==2):
		return 0
	if(n%2==0):
		return 1
	return 0
def ans(n,m):
	mp={}
	mp[0]=0
	mp[1]=1
	mp[2]=2
	mp[3]=3
	mp[4]=2
	mp[5]=1
	if(m==1):
		return mp[n%6]
	if(m==2):
		if(n==3):
			return 2
		if(n==2):
			return 4
		if(n==7):
			return 2
	return (n*m)%2

n,m=map(int,raw_input().split(" "))
n1=n
m1=m
if(n<m):
	(n,m)=(m,n)
print n*m-ans(n,m)


N,M = map(int,input().split())
l = [0,1,2,3,2,1]

res = float('inf')

for (n,m) in ((N,M),(M,N)):
    if l[n%6]==0:
        print(n*m)
        exit()
    elif l[n%6]==1:
        tmp = l[m%6]
        res = min(res,tmp)
    elif l[n%6]==2:
        if m>=4 and m!=7:
            print(n*m)
            exit()
        if m==2:
            tmp = 4
        else:
            tmp = 2
        res = min(res,tmp)
    else:
        if m==1:
            tmp = 3
        elif m==2:
            tmp = 2
        elif m%2==0:
            print(n*m)
            exit()
        else:
            tmp = 1
        res = min(res,tmp)

print(n*m-res)


r = lambda: raw_input().strip()

def check_possibility(new_position, M):
    if len(M) == 0:
        print 'WIN'
        exit()
    candidate_moves = []
    for c in [(0,0),(-1,0),(1,0),(0,1),(0,-1),(-1,-1),(-1,1),(1,-1),(1,1)]:
        new_coord = (new_position[0]+c[0], new_position[1]+c[1])
        if 0 <= new_coord[0] <= 7 and 0 <= new_coord[1] <= 7:
            candidate_moves.append(new_coord)
    candidate_moves = [c for c in candidate_moves if c not in M.keys()]
    M = dict([[(c[0],c[1]+1),'S'] for c in M.keys() if c[1]<7])
    candidate_moves = [c for c in candidate_moves if c not in M.keys()]
    for c in candidate_moves:
        check_possibility(c, dict(M.items()))

statue_locations = {}
for i in xrange(8):
    row = list(r())
    for j in xrange(8):
        if row[j] == 'S':
            statue_locations[(j,i)] = row[j]

check_possibility((0,7), dict(statue_locations.items()))
print 'LOSE'


r, s = [63], ''.join(input() + 'T' for i in range(8)) + 'T' * 9
for i in range(0, 72, 9):
    t = set()
    for x in r:
        for y in (x, x - 1, x + 1, x - 9, x + 9, x - 10, x - 8, x + 10, x + 8):
            if s[y] == 'T': continue
            if (y < i or s[y - i] != 'S') and (y < i + 9 or s[y - i - 9] != 'S'): t.add(y)
    r = t
print('WIN' if r else 'LOSE')


from itertools import permutations
nums = list(map(int, input().split()))
o = input().split()
print(min(eval("min(((a{0}b){1}c){2}d,(a{0}b){2}(c{1}d))".format(*o)) for a, b, c, d in permutations(nums)))


from itertools import *
l = map(int,raw_input().strip().split())
ops = raw_input().strip().split()

op = lambda o, a, b: a*b if o=='*' else a+b

print min(\
    min(op(ops[2],op(ops[1],op(ops[0],p[0],p[1]),p[2]),p[3]) for p in permutations(l,4)),\
    min(op(ops[2],op(ops[0],p[0],p[1]),op(ops[1],p[2],p[3])) for p in permutations(l,4)))


[h,m,s,t1,t2] = [int(x) for x in input().split()]
hh = h + m/60 + s/3600
mm = m/5
ss = s/5

ll = [hh,mm,ss,t1,t2]
ll = sorted(ll)

diff = abs(ll.index(t1)-ll.index(t2))
if diff==1 or diff==4:
    print('YES')
else:
    print('NO')

# Made By Mostafa_Khaled


h,m,s,t1,t2=map(int,input().split())
m+=s/60
h+=m/60
m/=5
s/=5
h=h%12
m=m%12
s=s%12
T1=min(t1,t2)
T2=max(t1,t2)
if(T1<h<T2 and T1<m<T2 and T1<s<T2):
    print("YES")
elif(not(T1<h<T2 or T1<m<T2 or T1<s<T2)):
    print("YES")
else:
    print("NO")


import sys
from array import array  # noqa: F401
from itertools import product

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n = int(input())
cand = set()

for i, (a, b, c) in enumerate(input().split() for _ in range(n)):
    a = list(map(int, a))
    b, c = int(b), int(c)
    s = set()

    for p in product(range(10), repeat=4):
        if len(set(p)) < 4:
            continue
        b_, c_ = 0, 0
        for j in range(4):
            if p[j] == a[j]:
                b_ += 1
            elif p[j] in a:
                c_ += 1
        if b == b_ and c == c_:
            s.add(''.join(map(str, p)))

    if i == 0:
        cand = s
    else:
        cand &= s

if len(cand) == 1:
    print(cand.pop())
elif len(cand) > 1:
    print('Need more data')
elif not cand:
    print('Incorrect data')
else:
    assert False


import sys
lines = sys.stdin.readlines()
n = int(lines[0].strip())
query = []
for i in range(1, n+1):
    (a, b, c) = lines[i].strip().split(" ")
    query.append((a, int(b), int(c)))
def compare(i):
    digits = str(i)
    digits = "0" *(4-len(digits)) + digits
    if len(set(list(digits))) != 4: return False
    for q in query:
        (a, b, c) = q
        m, n = 0, 0
        for i in range(4):
            if a[i] == digits[i]: m += 1
        for l in a:
            if l in digits: n += 1
        n -= m
        if m != b or n != c:
            return False
    return True
res = 0
count = 0
for i in range(123, 9877):
    if compare(i): count += 1; res = i
    if count >= 2: break
if count == 0: print("Incorrect data")
elif count == 1:
    digits = str(res)
    digits = "0" *(4-len(digits)) + digits
    print(digits)
else: print("Need more data")


n, k = map(int, input().split())
num = list(input())
if k == 0:
    print(*num, sep='')
    exit()
if n == 1:
    print('0')
    exit()
if num[0] != '1':
    num[0] = '1'
    k -= 1
for i, f in enumerate(num):
    if k > 0 and i > 0:
        if num[i] != '0':
            num[i] = '0'
            k -= 1
print(*num, sep='')


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

s = list(input())
if n == 1 and k:
    print("0")
    exit()
if k:
    for i in range(n):
        if not(i):
            if k and s[i] != "1":
                s[i] = "1"
                k -= 1
        else:
            if k:
                if s[i] != "0":
                    s[i] = "0"
                    k -= 1
            else:
                break
print("".join(s))


#codeforces 86a: reflection: math
l,r=map(int,input().split())

def digits(x):
	d=0
	while (x):
		d+=1
		x//=10
	return d

def f(n):
	return n*(10**digits(n)-1-n)

def maxInDigits(l,r):
	#print("dealwith",l,r)
	mid=10**digits(l)//2
	if (r<=mid): return f(r)
	if (l>=mid): return f(l)
	return f(mid)

if (digits(l)==digits(r)): print(maxInDigits(l,r))
else:
	ans=max(maxInDigits(l,10**digits(l)-1),maxInDigits(10**(digits(r)-1),r))
	if (digits(r)-1>digits(l)):
		ans=max(ans,maxInDigits(10**(digits(r)-2),10**(digits(r)-1)-1))
	print(ans)


def reflection(num):
    tmp = []
    numlist = list(str(num))
    for el in numlist:
        i = int(el)
        ni = 9-i
        if ni == 0 and len(tmp) == 0:
            continue
        tmp.append(str(ni))
    if not tmp:
        return 0
    return int("".join(tmp))

def solve(l, r):
    result = 0
    result = max(result, l*reflection(l))
    result = max(result, r*reflection(r))

    start = 0
    while 5*(10**start) <= l:
        start += 1

    while 5*(10**start) <= r:
        cur_num = 5*(10**start)
        result = max(result, cur_num*reflection(cur_num))
        start += 1
    return result

l, r = map(int, input().split())
result = solve(l, r)
print(result)