source_code:
def pow3(N, M):
  if N == 0:
    return 0
  if N == 1:
    return 3 % M
  res = pow3(N / 2, M) ** 2
  if N % 2 == 1:
    res *= 3
  return res % M

def solve(N, M):
  return (pow3(N, M) + M - 1) % M

import sys
input = sys.stdin
N, M = map(int, input.readline().split())
print solve(N, M)

lang_cluster: Python

exec_outcome: PASSED


source_code:
import math
n = int(input())
a = [int(i) for i in input().split() ]
avr = 0
a.sort()
for i in a:
    avr += i
avr = avr / n
if avr-4.5 >=0:
    print(0)
else:
    num = 4.5 - avr
    num = num * n
    if abs(int(num)-num)>0.0000001:
        num = math.ceil(num)
    else:
        num = int(num)
    cnt = 0
    for i in a:
        num += i - 5
        cnt += 1
        if num <= 0:
            break
    print(cnt)


source_code:
li=map(int,raw_input().split())

"""initially number shows n"""

n=li[0]
m=li[1]

count=0

while n<m:
    if m%2==0:
        m=m/2
    else:
        m=m+1
    count=count+1

print count+(n-m)


source_code:
n , k = map(int,input().split())
l = -1
h = n + 1
while l + 1 < h:
    mid = (l + h) // 2
    if 2 * (mid + k * mid) <= n:
        l = mid
    else:
        h = mid
print(l , k * l , n - (l + k * l))


source_code:
s = input()
print(min(len(s), s.count('a')*2-1))


source_code:
from itertools import accumulate as _accumulate
import sys as _sys

def main():
    n, k = _read_ints()
    s = input()
    t = input()
    result = find_best_score_can_make(s, t, moves_n=k)
    print(result)

def _read_ints():
    return map(int, _sys.stdin.readline().split(" "))

_A = "a"
_B = "b"
_C = "c"

def find_best_score_can_make(s, t, moves_n):
    assert len(t) == 2
    if t[0] == t[1]:
        t_char = t[0]
        t_char_count = s.count(t_char)
        t_char_count += moves_n
        if t_char_count > len(s):
            t_char_count = len(s)
        return t_char_count * (t_char_count - 1) // 2

    s = [(_A, _B)[t.index(char)] if char in t else _C for char in s]
    s = ''.join(s)
    del t

    a_indices, b_indices, c_indices = _compute_abc_indices(s)

    best_score = -float("inf")

    max_c_start = min(len(c_indices), moves_n)
    for c_start in range(0, max_c_start+1):
        c_start_moves_spent = c_start
        moves_spent = c_start_moves_spent
        moves_remain = moves_n - moves_spent
        assert moves_remain >= 0

        max_b_start = min(len(b_indices), moves_remain)
        for b_start in range(0, max_b_start+1):
            b_start_moves_spent = b_start
            moves_spent = c_start_moves_spent + b_start_moves_spent
            moves_remain = moves_n - moves_spent
            assert moves_remain >= 0

            new_s = list(s)
            for i_i_c in range(0, c_start):
                i_c = c_indices[i_i_c]
                new_s[i_c] = _A
            for i_i_b in range(0, b_start):
                i_b = b_indices[i_i_b]
                new_s[i_b] = _A

            curr_best_score = _find_best_score_can_make_with_fixed_starts(new_s, moves_remain)
            best_score = max(best_score, curr_best_score)

    return best_score

def _compute_abc_indices(s):
    a_indices = []
    b_indices = []
    c_indices = []
    for i_char, char in enumerate(s):
        if char == _A:
            a_indices.append(i_char)
        elif char == _B:
            b_indices.append(i_char)
        else:
            assert char == _C
            c_indices.append(i_char)
    return a_indices, b_indices, c_indices

def _find_best_score_can_make_with_fixed_starts(s, moves_n):
    s = list(s)

    best_score = -float("inf")

    a_indices, b_indices, c_indices = _compute_abc_indices(s)

    a_n = len(a_indices)
    c_n = len(c_indices)

    max_a_stop = len(a_indices)
    max_c_stop = len(c_indices)

    def get_c_stop_by_moves_remain(moves_remain):
        min_c_stop = max_c_stop - moves_remain
        if min_c_stop < 0:
            min_c_stop = 0
        c_stop = min_c_stop
        return c_stop

    first_c_stop = get_c_stop_by_moves_remain(moves_n)
    new_s = _get_curr_s(s, a_indices, max_a_stop, c_indices, first_c_stop)
    curr_score = _get_curr_score_slow_way(new_s)

    best_score = max(best_score, curr_score)

    old_a_before = _compute_a_before(new_s)
    old_b_after_if_all_c_are_b = _compute_b_after(''.join(new_s).replace(_C, _B))

    curr_b_to_c_before_a = 0
    curr_a_to_b_after_c = 0

    prev_c_stop = None
    c_stop = first_c_stop
    c_stop_moves_spent = max_c_stop - c_stop

    min_a_stop = max_a_stop - moves_n
    min_a_stop = max(min_a_stop, 0)
    for a_stop in reversed(range(min_a_stop, max_a_stop-1 + 1)):
        a_stop_moves_spent = max_a_stop - a_stop
        moves_spent = a_stop_moves_spent
        moves_remain = moves_n - moves_spent
        assert moves_remain >= 0

        # a_stop update processing

        # s[a_indices[a_stop]]: _A -> _B
        # curr_score -= b_after[a_indices[a_stop]]
        # curr_score += a_before[a_indices[a_stop]]
        # prev_a_stop - a_stop == 1
        assert a_stop_moves_spent > 0

        curr_a_index = a_indices[a_stop]
        curr_b_to_c = c_stop
        if curr_b_to_c_before_a < curr_b_to_c \
                and c_indices[curr_b_to_c_before_a] < curr_a_index:
            while curr_b_to_c_before_a < curr_b_to_c \
                    and c_indices[curr_b_to_c_before_a] < curr_a_index:
                curr_b_to_c_before_a += 1
        elif curr_b_to_c_before_a > 0 \
                and c_indices[curr_b_to_c_before_a-1] > curr_a_index:
            while curr_b_to_c_before_a > 0 \
                    and c_indices[curr_b_to_c_before_a-1] > curr_a_index:
                curr_b_to_c_before_a -= 1

        prev_a_stop_moves_spent = a_stop_moves_spent - 1  # exclude curr move
        curr_b_to_c_after_a = curr_b_to_c - curr_b_to_c_before_a
        new_b_after = prev_a_stop_moves_spent - curr_b_to_c_after_a
        b_after = old_b_after_if_all_c_are_b[curr_a_index] + new_b_after
        curr_score -= b_after
        curr_score += old_a_before[curr_a_index]

        # c stop update

        prev_c_stop = c_stop
        c_stop = get_c_stop_by_moves_remain(moves_remain)
        c_stop_moves_spent = max_c_stop - c_stop

        # c_stop update processing

        assert c_stop - prev_c_stop in (0, 1)
        if c_stop - prev_c_stop == 1:
            # s[c_indices[prev_c_stop]]: _B -> _C
            # curr_score -= a_before[c_indices[prev_c_stop]]
            assert 0 <= prev_c_stop < len(c_indices)

            prev_c_index = c_indices[prev_c_stop]
            curr_a_to_b = a_n - a_stop
            if curr_a_to_b_after_c < curr_a_to_b \
                    and a_indices[a_n - (curr_a_to_b_after_c + 1)] > prev_c_index:
                while curr_a_to_b_after_c < curr_a_to_b \
                        and a_indices[a_n - (curr_a_to_b_after_c + 1)] > prev_c_index:
                    curr_a_to_b_after_c += 1
            elif curr_a_to_b_after_c > 0 \
                    and a_indices[a_n - curr_a_to_b_after_c] < prev_c_index:
                while curr_a_to_b_after_c > 0 \
                        and a_indices[a_n - curr_a_to_b_after_c] < prev_c_index:
                    curr_a_to_b_after_c -= 1

            a_to_b_before = curr_a_to_b - curr_a_to_b_after_c
            curr_a_before = old_a_before[prev_c_index] - a_to_b_before
            curr_score -= curr_a_before

        # saving result
        best_score = max(best_score, curr_score)

    return best_score

def _get_curr_s(s, a_indices, a_stop, c_indices, c_stop):
    s = list(s)
    for i_i_a in range(a_stop):
        i_a = a_indices[i_i_a]
        s[i_a] = _A
    for i_i_a in range(a_stop, len(a_indices)):
        i_a = a_indices[i_i_a]
        s[i_a] = _B
    for i_i_c in range(c_stop):
        i_c = c_indices[i_i_c]
        s[i_c] = _C
    for i_i_c in range(c_stop, len(c_indices)):
        i_c = c_indices[i_i_c]
        s[i_c] = _B
    return s

def _get_curr_score_slow_way(s):
    curr_score = 0
    a_accumulated = 0
    for char in s:
        if char == _A:
            a_accumulated += 1
        elif char == _B:
            curr_score += a_accumulated
    return curr_score

def _compute_a_before(s):
    result = tuple( _accumulate(int(char == _A) for char in s) )
    result = (0,) + result[:-1]
    return result

def _compute_b_after(s):
    result = tuple( _accumulate(int(char == _B) for char in s[::-1]) )[::-1]
    result = result[1:] + (0,)
    return result

if __name__ == '__main__':
    main()


source_code:
a=int(input())
print (a/2)+1


source_code:
import sys,math
n=int(input())
s=input()
ans=0
i=n-1
flag=True
while(i>=0):
    if i%2==1 and s[:i//2+1]==s[i//2+1:i+1] and flag:
        ans+=1
        i//=2
        flag=False
    else:
        i-=1
        ans+=1
print(ans)


source_code:
s = input()
a = ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
print (['No', 'Yes'][any(i in s for i in a)])


source_code:
n = int(input())
t = -1
an = 0
a = list(map(int, input().split()))
while a.count(1):
    an = max(a.index(1) + a.count(1), an)
    del a[a.index(1)]

print(max(an, len(a)))


source_code:
from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii():  return int(input())
def si():  return input()
def mi():  return map(int,input().split(" "))
def msi(): return map(str,input().split(" "))
def li():  return list(mi())

def dmain():
    sys.setrecursionlimit(1000000)
    threading.stack_size(1024000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import log,sqrt,factorial,cos,tan,sin,radians
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list  m = [x[:] for x in mark] .. Avoid Using Deepcopy

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1]
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))

def ceil(x,y):
    if x%y==0:
        return x//y
    else:
        return x//y+1

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def calc(x,n):
    c=0
    while x>0:
        if x>=n:
            x-=n
            c+=1
        elif x>=(n-1):
            x-=(n-1)
            c+=1
        elif x>=(n-2):
            x-=(n-1)
            c+=1
        elif x>=(n-3):
            x-=(n-1)
            c+=1
        else:
            x-=1
            c+=1
    return c
def calc1(x,n):
    c=0
    while x>0:
        if x>=n:
            x-=n
            c+=1
        elif x>=(n-1):
            x-=(n-1)
            c+=1
        elif x>=(n-2):
            x-=(n-1)
            c+=1
        else:
            x-=1
            c+=1
    return c
def calc2(x,n):
    c=0
    while x>0:
        if x>=n:
            x-=n
            c+=1
        elif x>=(n-1):
            x-=(n-1)
            c+=1
        else:
            x-=1
            c+=1
    return c
def calc3(x,n):
    c=0
    while x>0:
        if x>=n:
            x-=n
            c+=1
        else:
            x-=1
            c+=1
    return c
def main():
    x=ii()
    if x>=5:
        res=calc(x,5)
    elif x>=4:
        res=calc1(x,4)
    elif x>=3:
        res=calc2(x,3)
    elif x>=2:
        res=calc3(x,2)
    else:
        res=x
    print (res)

# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()


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

if m <= n // 2: a = m + 1
else: a = m - 1
if a > n: a = n
if a < 1: a = 1
print(a)


source_code:
INT=lambda:int(input())
a=INT()
b=INT()
c=INT()
d=INT()
e=INT()
f=INT()
if e>f:
	m=min(a,d)*e
	d-=min(a,d)
	m+=min(b,c,d)*f
elif e<f:
	m=min(b,c,d)*f
	d-=min(b,c,d)
	m+=min(a,d)*e
else:
	if min(a,b)<min(b,c,d):
		m=min(b,c,d)*f
		d-=min(b,c,d)
		m+=min(a,d)*e
	else:
		m=min(a,d)*e
		d-=min(a,d)
		m+=min(b,c,d)*f
print(m)


source_code:
"""
// Author : snape_here - Susanta Mukherjee

"""

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

mod=1000000007

def main():

    x1,y1,x2,y2=mi()
    x,y=mi()
    a=x2-x1
    b=y2-y1
    if a%x or b%y:
        print("NO")
    else:
        c=a//x
        d=b//y
        if abs(c-d)%2:
            print("NO")
        else:
            print("YES")

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

# endregion

if __name__ == "__main__":
    #read()
    main()


source_code:
import math
n=int(input())
a=int(input())
b=int(input())
list=[a]*4+[b]*2
M=max([a,b])
m=min([a,b])
if n<2*m:
    print 6
elif 2*m<=n and n<m+M:
    print int(math.ceil(float(list.count(m))/(n/m)))+list.count(M)
elif m+M<=n:
    if a>=b:
        if 2*a>n:
            print 4
        elif 2*a<=n<3*a:
            bd=n%a
            if bd>=b:
                print 2
            else:
                print 3
        elif 3*a<=n<4*a+2*b:
            print 2
        elif 4*a+2*b<=n:
            print 1
    elif a<b:
        if n<b+2*a:
            print 3
        elif n>=4*a+2*b:
            print 1
        else:
            print 2


source_code:
n = int(input())
s = list(input())
if '8' not in s:
     print(0)
     exit()
print(min(s.count('8') , n // 11))


source_code:
# python 3
"""
Read tutorial, graph the moves
"""

def inna_and_pink_pony(n_int, m_int, i_int, j_int, a_int, b_int) -> str:
    corner_1 = (1, 1)
    corner_2 = (1, m_int)
    corner_3 = (n_int, 1)
    corner_4 = (n_int, m_int)
    corners = [corner_1, corner_2, corner_3, corner_4]
    c = max(n_int, m_int)
    for each in corners:
        if abs(each[0] - i_int) % a_int != 0 or abs(each[1] - j_int) % b_int != 0:
            continue
        horizontal_moves = abs(each[0] - i_int) // a_int
        vertical_moves = abs(each[1] - j_int) // b_int
        if horizontal_moves % 2 != vertical_moves % 2:
            continue
        each_move = max(horizontal_moves, vertical_moves)
        if (a_int > max(i_int - 1, n_int - i) and abs(each[1] - j_int) > 0) or (
                b_int > max(j - 1, m - j) and abs(each[0] - i_int) > 0):
            break
        c = min(c, each_move)

    if c < max(n_int, m_int):
        return c
    else:
        return "Poor Inna and pony!"

if __name__ == "__main__":
    """
    Inside of this is the test.
    Outside is the API
    """

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

    print(inna_and_pink_pony(n, m, i, j, a, b))

    # print(inna_and_pink_pony(n, m, i, j, a, b))


source_code:
a , b = map(int,input().split())

cnt = 1
ans = [b]
flag = True
while b > a :
    r = b % 10
    if r % 2 == 0 :
         b //= 2
         cnt +=1
         ans.append(b)

    else:
        if b % 10 % 2 != 0 and b % 10 != 1 :
            flag = False
            break
        else:
            b //= 10
            ans.append(b)
            cnt +=1

#print(b)
if flag and a == b:
    print('YES')
    print(cnt)
    ans = list(reversed(ans))
    print(*ans)

else:
    print('NO')


source_code:
from sys import stdin,stdout
from itertools import combinations
from collections import defaultdict,OrderedDict
import math
import heapq

def listIn():
    return list((map(int,stdin.readline().strip().split())))

def stringListIn():
    return([x for x in stdin.readline().split()])

def intIn():
    return (int(stdin.readline()))

def stringIn():
    return (stdin.readline().strip())

def nCr(n,k):
    if(k > n - k):
        k = n - k
    # initialize result
    res = 1
    # Calculate value of
    # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]
    for i in range(k):
        res = res * (n - i)
        res = res // (i + 1)
    return res

if __name__=="__main__":
    n,m,k=listIn()
    mod=998244353

    #ways to select bricks
    selection=(nCr(n-1,k))%mod
    colors_ways=m*((m-1)**k)%mod #ways to select m-1 colors

    total_ways=colors_ways*selection
    print(total_ways%mod)


source_code:
people, seconds = map(int, input().split())
prev, cur = input(), ""

while seconds > 0:
    idx = 0
    while idx < people:
        if idx == people - 1:
            cur += prev[idx]
            break

        if prev[idx] == "B" and prev[idx+1] == "G":
            cur += "G"
            cur += "B"
            idx += 1
        else:
            cur += prev[idx]

        idx += 1

    prev = cur
    cur = ""
    seconds -= 1

print(prev)


source_code:
n, m, a, b = [int(x) for x in raw_input().split()]
ans = min(n%m * b, (m - n%m)%m * a)
print ans


source_code:
import atexit
import io
import sys
import math

# Buffering IO
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

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

def main():
    n = int(input())
    ss = 0

    k = 1
    while n>1:
        ss += k * (n // 2)
        n = math.ceil(n/2)
        k*=2

    print(ss)

if __name__ == '__main__':
    main()


source_code:
import math
xo,yo,ax,ay,bx,by=map(int,input().split())
orx,ory=xo,yo
xs,ys,t=map(int,input().split())
cur=abs(xo-xs)+abs(yo-ys)
sort=[cur]
while True:
    x,y=xo,yo
    xo,yo=ax*xo+bx,ay*yo+by
    cur=abs(xo-xs)+abs(yo-ys)
    if cur>sort[-1]:
        break
    else:
        sort.append(cur)
dpoint=0
copyx,copyy=x,y
mina=abs(x-xs)+abs(y-ys)
if mina<=t:
    dpoint+=1
time=0
copy=time
while time<t and (x,y)!=(orx,ory):
    a,b=x,y
    x,y=(x-bx)//ax,(y-by)//ay
    time+=abs(x-a)+abs(y-b)
    if (time+min(mina,abs(x-xs)+abs(y-ys)))<=t:
        dpoint+=1
    #print(x,y,a,b,time,dpoint)
if time+min(mina,(abs(x-xs)+abs(y-ys)))<t:
    mina=abs(x-xs)+abs(y-ys)
    while time<t:
        a,b=ax*copyx+bx,ay*copyy+by
        time+=abs(a-copyx)+abs(b-copyy)
        copyx,copyy=a,b
        x,y=a,b
        if (time+min(mina,(abs(a-xs)+(b-ys))))<=t:
            #print(time+min(mina,(abs(a-xs)+(b-xs))),a,b,copyx,copyy,dpoint)
            dpoint+=1
print(dpoint)


source_code:
a, b, c = map(int, input().split())
x = (a * c * b) ** .5
print(4 * int(x / a + x / b + x / c))


source_code:
def sol():

    N = int(input())
    count = 1

    if N == 1:
        print(1)
        return

    while N > 3:
        N = N//2
        count += 1

    count += 1

    print(count)

# main
#for t in range(100):
sol()


source_code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline

MOD = 998244353
MAX_N = 2 * 10**5 + 1
n, m = map(int, input().split())

# Construct factorial table
fac = [1] + [0] * MAX_N
for i in range(1, MAX_N+1):
    fac[i] = fac[i-1] * (i) % MOD

fac_inv = [1] + [0] * MAX_N
fac_inv[MAX_N] = pow(fac[MAX_N], MOD-2, MOD)
for i in range(MAX_N, 1, -1):
    fac_inv[i-1] = fac_inv[i] * i % MOD

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

if n-3 > 0:
    ans = mod_nCr(m, n-1) * (n-2) * pow(2, n-3, MOD)
else:
    ans = mod_nCr(m, n-1) * (n-2)
ans %= MOD
print(ans)


source_code:
n, k = map(int, input().split(" "))

i = 2
table = []
while i * i <= n:
    while n % i == 0:
        n //= i
        table.append(i)

    i += 1

if n > 1:
    table.append(n)

if len(table) >= k:
    ans = []
    for j in range(k-1):
        ans.append(table[j])

    tmp = 1
    for j in range(k-1, len(table)):
        tmp *= table[j]

    ans.append(tmp)
    print(" ".join(map(str,ans)))
else:
    print(-1)


source_code:
n,m = map(int,input().split())
f=0
if n>=m:
    if n%2==0:
       for i in range(n//2,n+1):
         if i%m==0:
          print(i)
          f=1
          break
    else:
        for i in range(n // 2 + 1, n + 1):
            if i % m == 0:
                print(i)
                f = 1
                break
elif m>n:
    print(-1)
elif f==0:
    print(-1)


source_code:
x,y,z,k=map(int,raw_input().split())
x,y,z = sorted([x,y,z])
x-=1
y-=1
z-=1
if x>k/3: x=k/3
k-=x
if y>k/2: y=k/2
k-=y
if z>k: z=k

print (x+1)*(y+1)*(z+1)


source_code:
a = input()
b = input()

d = {}
for e in b:
    if e == '9':
        e = '6'
    if e == '5':
        e = '2'
    if e in d:
        d[e] = d[e] + 1
    else:
        d[e] = 1

n = {}
for e in a:
    if e == '9':
        e = '6'
    if e == '5':
        e = '2'
    if e in n:
        n[e] += 1
    else:
        n[e] = 1
result = 10000000
for e in n:
    if e not in d:
        result = 0
        break
    else:
        temp_result = int(d[e] / n[e])
        if temp_result < result:
            result = temp_result

print(result)


source_code:
n=int(input())
curr=list([i for i in range(1,100)])
curr=set(curr)
def isvalid(x):
    if x<1 or x>10**9:
        return 0
    if len(set(str(x)))<=2:
        return 1
cnt=0
while cnt<=10**5 :
    curr1=set()
    for i in curr:
        for j in range(10):
            if isvalid(i*10+j):
                curr1.add(i*10+j)
               # print('hi')
                cnt+=1
    #print(curr1)
    curr|=curr1
curr=sorted(list(curr))
#print(curr)
ans=0
for i in curr:
    if i>=1 and i<=n:
        ans+=1
    elif i>n:
        break
print(ans)


source_code:
big = 100010
def gen_mu():
    mu = [1]*big
    mu[0] = 0
    P = [True]*big
    P[0] = P[1] = False
    for i in range(2,big):
        if P[i]:
            j = i
            while j<big:
                P[j] = False
                mu[j] *= -1
                j += i
            j = i*i
            while j<big:
                mu[j] = 0
                j += i*i
    return mu

m = int(input())
mu = gen_mu()

MOD = 10**9+7
def mod_inv(x):
    return pow(x, MOD-2, MOD)

s = 1
for i in range(2,big):
    # p is probabilty that i | a random number [1,m]
    p = (m//i)*mod_inv(m)
    s += (-mu[i])*(p)*mod_inv(1-p)
print(s%MOD)


source_code:
def aux(x, a, b, i, vis):
	stack = [i]
	while stack:
		i = stack.pop()
		if i-b >= 0 and i-b not in vis:
			vis.add(i-b)
			stack.append(i-b)
		if i+a <= x and i+a not in vis:
			vis.add(i+a)
			stack.append(i+a)

def single(x, a, b, vis):
	if x-a in vis:
		vis.add(x)
		aux(x, a, b, x, vis)
	return len(vis)

def sum_seq(n):
	return n * (n+1) / 2

def solve(m, a, b):
	vis = set([0])
	tot = 0
	for i in xrange(m+1):
		one = single(i, a, b, vis)
		tot += one
		if i > 0 and one == i + 1:
			return tot + sum_seq(m+1) - sum_seq(i+1)
	return tot

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

def solve_good(m, a, b):
	g = gcd(a, b)
	first = min(m, a+b)
	vis = set([0])
	tot = 0
	for i in xrange(first+1):
		ct = single(i, a, b, vis)
		tot += ct
	tot += g * (sum_seq((m-first)/g + ct) - sum_seq(ct))
	if (m-first) / g > 0:
		tot -= ((m-first)/g + ct) * ((g-1) - (m-first) % g)
	tot += ct * min(g-1, m-first)
	return tot

m, a, b = map(int, raw_input().split())
print solve_good(m, a, b)


source_code:
n = int(raw_input())
mod = 10 ** 9 + 7

limit = 2 * n + 1
not_prime = (limit + 1) * [ False ]
not_prime[0] = not_prime[1] = True
primes = []
for i in range(limit + 1):
    if not_prime[i]:
        continue
    primes.append(i)
    for j in range(i * i, limit + 1, i):
        not_prime[j] = True

def choose_mod(m, n, mod):
    n = min(n, m - n)
    factors = len(primes) * [ 0 ]
    for pos, x in enumerate(primes):
        if x > m:
            break
        for i in range(x, m + 1, x):
            if i > n and i <= m - n:
                continue
            y = i
            c = 0
            while y % x == 0:
                y //= x
                c += 1
            if i <= n:
                factors[pos] -= c
            else:
                factors[pos] += c
    result = 1
    for pos, x in enumerate(factors):
        y = primes[pos]
        for i in range(x):
            result = (result * y) % mod
    return result

print((2 * choose_mod(2 * n + 1, n, mod) - 1) % mod)


source_code:
from math import trunc

MOD = 998244353
MODF = float(MOD)
SHRT = float(1 << 16)
G = 3.0
MAXSIZ = 1 << 20

# Using pajenegod's crazy method for multiplication using floating point
fmod = lambda x: x - MODF * trunc(x / MODF)
mod_prod = lambda a, b: fmod(trunc(a / SHRT) * fmod(b * SHRT) + (a - SHRT * trunc(a / SHRT)) * b)
def fpow(a, b):
    r = 1.0
    while b:
        if b & 1: r = mod_prod(r, a)
        if b > 1: a = mod_prod(a, a)
        b >>= 1
    return r

n, k = map(int, raw_input().split())
f = [0.0] * MAXSIZ
for d in map(int, raw_input().split()):
    f[d] = 1.0

m = MAXSIZ
m2 = m / 2
w = [1] * m2
w[1] = fpow(G, (MOD - 1) / m)
for i in xrange(2, m2):
    w[i] = mod_prod(w[i - 1], w[1])

rev = [0] * m
for i in xrange(m):
    rev[i] = rev[i >> 1] >> 1
    if i & 1: rev[i] |= m2

def ntt_transform(a):
    for i in xrange(m):
        if i < rev[i]: a[i], a[rev[i]] = a[rev[i]], a[i]
    l = 2
    while l <= m:
        half, diff = l >> 1, m / l
        for i in xrange(0, m, l):
            pw = 0
            for j in xrange(i, i + half):
                v = mod_prod(a[j + half], w[pw])
                a[j + half] = a[j] - v
                a[j] = a[j] + v
                pw += diff
        l <<= 1

ntt_transform(f)
f = [fpow(x, n >> 1) for x in f]
ntt_transform(f)

inv_m = fpow(m, MOD - 2)
ans = mod_prod(sum(mod_prod(x, x) for x in f) % MODF, mod_prod(inv_m, inv_m))
print(int(ans))