Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games.BitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of n non-negative integers a1, a2, ..., an. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn:  Take one of the integers (we'll denote it as ai). Choose integer x (1 ≤ x ≤ ai). And then decrease ai by x, that is, apply assignment: ai = ai - x.  Choose integer x . And then decrease all ai by x, that is, apply assignment: ai = ai - x, for all i. The player who cannot make a move loses.You're given the initial sequence a1, a2, ..., an. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.

The first line contains an integer n (1 ≤ n ≤ 3). The next line contains n integers a1, a2, ..., an (0 ≤ ai < 300).

Write the name of the winner (provided that both players play optimally well). Either "BitLGM" or "BitAryo" (without the quotes).

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
    if ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    ch=[0]*(785)
    for i in range(300):
        a=floor(phi*i)
        b=floor((phi**2)*i)
        ch[a]=b
        ch[b]=a
    if ch[li[0]]==li[1]:
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=int(input())
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")

G = (1 + 5 ** .5) / 2
w = set((int(k * G), int(k * G) + k) for k in range(999))
n = input()
a = sorted(map(int, raw_input().split()))
print ["BitLGM", "BitAryo"][n == 2 and (a[0], a[1]) in w or n != 2 and not reduce(lambda x, y : x ^ y, a)]

G = (1 + 5 ** .5) / 2
w = set((int(k * G), int(k * G) + k) for k in range(999))
n = input()
a = sorted(map(int, raw_input().split()))+[0,0]
print 'BitAryo' if (((a[0], a[1]) in w) if 2==n else not(a[0]^a[1]^a[2])) else 'BitLGM'

def main():
    n = int(raw_input())
    a = map(int, raw_input().split())
    a.sort()
    if n == 1:
        print "BitLGM" if a[0] else "BitAryo"
    elif n == 3:
        print "BitLGM" if a[0] ^ a[1] ^ a[2] else "BitAryo"
    else:
        d = set([(0, 0)])
        g = set()
        g.add(0)
        prev = [0, 0]
        i = 1
        while i < 300:
            if i not in g:
                prev[1] += i - prev[0] + 1
                prev[0] = i
                d.add(tuple(prev))
                g.add(prev[0])
                g.add(prev[1])
            i += 1
        print "BitLGM" if tuple(a) not in d else "BitAryo"
main()

#!/usr/bin/env python2

occ = []
for i in range(300):
    occ.append(0)
pair = {}
k = 0
i = 0
while i < 300:
    while i < 300 and occ[i] == 1:
        i += 1
    if i == 300:
        break
    occ[i] = 1
    if i+k < 300:
        occ[i+k] = 1
    pair[i] = i+k
    k += 1
#print pair

n = int(raw_input())

if n == 1:
    a = int(raw_input())
    if a == 0:
        print "BitAryo"
    else:
        print "BitLGM"

elif n == 2:
    a, b = map(int, raw_input().split())
    if (a in pair and pair[a] == b) or (b in pair and pair[b] == a):
        print "BitAryo"
    else:
        print "BitLGM"

else:
    a, b, c = map(int, raw_input().split())
    if (a^b^c) == 0:
        print "BitAryo"
    else:
        print "BitLGM"

n = input()
ans = 1
if n == 1:
	a = input()
	if a == 0:
		ans = 2
if n == 2:
	a, b = sorted(map(int, raw_input().split()))
	x = (5 ** 0.5 - 1) / 2
	y = (5 ** 0.5 + 1) / 2
	z = int(a * x)
	if a == int(z * y):
		if b == a + z:
			ans = 2
	if a == int((z + 1) * y):
		if b == a + z + 1:
			ans = 2
if n == 3:
	a, b, c = map(int, raw_input().split())
	if a ^ b ^ c == 0:
		ans = 2
if ans == 1:
	print "BitLGM"
else:
	print "BitAryo"

dp=[]
for i in xrange(333):
    tmp = []
    for j in xrange(333):
        tmp.append(0)
    dp.append(tmp)

n = map(int,raw_input().split())[0]
a = map(int,raw_input().split())
s1="BitLGM"
s2="BitAryo"

if n==2:
    dp[0][0]=0
    for i in xrange(302):
        for j in xrange(302):
            if(dp[i][j]==0):
                k=1
                while i+k<=300:
                    dp[i+k][j]=1
                    k=k+1
                k=1
                while j+k<=300:
                    dp[i][j+k]=1
                    k=k+1
                k=1
                while i+k<=300 and j+k<=300:
                    dp[i+k][j+k]=1
                    k=k+1
    if dp[a[0]][a[1]]==1:
        print s1
    else: print s2
    exit(0)

t = 0
if n==1: t = a[0]
else:
    t = (a[0]^a[1]^a[2])

if(t>0):
    print s1
else:
    print s2

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
        if i==0:
            flag=1
    if flag==1 and ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    ch=[0]*(785)
    for i in range(300):
        a=floor(phi*i)
        b=floor((phi**2)*i)
        ch[a]=b
        ch[b]=a
    if ch[li[0]]==li[1]:
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=int(input())
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
        if i==0:
            flag=1
    if flag==1 and ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    ch=[0]*(600)
    for i in range(100):
        a=floor(phi*i)
        b=floor((phi**2)*i)
        ch[a]=b
        ch[b]=a
    if ch[li[0]]==li[1]:
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=int(input())
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
        if i==0:
            flag=1
    if flag==1 and ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    ch=[0]*(600)
    for i in range(100):
        a=floor(phi*i)
        b=floor((phi**2)*i)
        ch[a]=b
        ch[b]=a
    if ch[li[0]]==li[1]:
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=input()
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
        if i==0:
            flag=1
    if flag==1 and ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    if floor((li[0]+1)/phi)==floor((li[1]+1)/(phi**2)):
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=input()
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")

input()
n = map(int, raw_input().split())
print ['BitAryo', 'BitLGM'][len(n) == 1 or (len(n) == 2 and n[0] == n[1]) or len(n) == 3]

dp=[]
for i in xrange(333):
    tmp = []
    for j in xrange(333):
        tmp.append(-1)
    dp.append(tmp)

n = map(int,raw_input().split())[0]
a = map(int,raw_input().split())
s1="BitLGM"
s2="BitAryo"

if n==2:
    dp[0][0]=0
    for i in xrange(302):
        for j in xrange(302):
            if(dp[i][j]==0):
                k=1
                while i+k<=300:
                    dp[i+k][j]=1
                    k=k+1
                k=1
                while j+k<=300:
                    dp[i][j+k]=1
                    k=k+1
                k=1
                while i+k<=300 and j+k<=300:
                    dp[i+k][j+k]=1
                    k=k+1
    if dp[a[0]][a[1]]==1:
        print s1
    else: print s2
    exit(0)

t = 0
if n==1: t = a[0]
else:
    t = (a[0]^a[1]^a[2])

if(t>0):
    print s1
else:
    print s2


An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.The spacecraft team consists of n aliens. Each of them is given a rank — an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m.

The first line contains two space-separated integers: n and m (1 ≤ n, m ≤ 109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.

Print a single number — the answer to the problem modulo m.

NoteIn the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.To briefly describe the movements in the second sample we will use value , which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: , , , , , , , , , , , , , , , , , , , , , , , , , ; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2.

n,m=map(int,input().split())
final=(pow(3,n,m)-1)
if final<0:
    print(m-1)
else:
    print(final)

#import sys
#
#sys.stdin = open('in.txt', 'r')

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

def cal(n):
    ret, tem = 1, 3
    while(n):
        if n & 1: ret = ret * tem % mod
        n >>= 1
        tem = tem * tem % mod
    return ret
print ((cal(n) - 1 + mod) % mod)

n, m = map(int, input().split())
print((pow(3,n,m)-1%m)%m)

'''input
3 8
'''
# practicing a skill right after sleep improves it a lot quickly
from sys import stdin, setrecursionlimit
import math

# main starts
n, m = list(map(int, stdin.readline().split()))
p = pow(3, n, m)
print((p - 1) % m)

a, b = map(int,raw_input().split())
print (pow(3, a, b) + b - 1)% b

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

def binpow(a, b, m):
    if (not b): return 1
    if (b == 1): return a%m
    ret = binpow(a, b//2, m)
    ret = (ret * ret)%m
    if (b&1): ret = (ret * (a%m))%m
    return ret

def main():
    n,m = [int(c) for c in input().split()]
    ret = binpow(3, n, m)
    ret = (ret - 1)%m
    print(str(ret) + '\n')
    return 0

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()

def fastpow(mod,times):
    if times==1:
        return 3
    else:
        if (times%2):
            now=fastpow(mod,(times-1)/2)%mod
            return (now*now*3)%mod
        else:
            now = fastpow(mod, (times ) / 2) % mod
            return (now * now ) % mod
n,m=map(int, input().split())
print((fastpow(m,n)-1)%m)

def power(a, n, m):
	if n==0: return 1
	if n==1: return a%m
	if n%2 == 0:
		x = power(a, n//2, m)
		return (x*x)%m
	else:
		x = power(a, n//2, m)
		return (((x*x)%m)*(a%m))%m

n, m = [int(x) for x in input().split()]
print((power(3, n, m)-1)%m)

from sys import stdin, stdout

# Read input: stdin.readline()
# Print output: stdout.write()

def binpow(a, b, m):
    if (not b): return 1
    if (b == 1): return a%m
    ret = binpow(a, b//2, m)
    ret = (ret * ret)%m
    if (b&1): ret = (ret * (a%m))%m
    return ret

def main(args):
    n,m = [int(c) for c in stdin.readline().split()]
    ret = binpow(3, n, m)
    ret = (ret - 1)%m
    stdout.write(str(ret) + '\n')
    return 0

if __name__ == '__main__':
	import sys
	sys.exit(main(sys.argv))

def fast_mod(a , n , m):
    ans = 1
    while n >= 1:
        if n % 2 == 1:
            ans = (ans * a) % m
        a = (a * a) % m
        n = n / 2
    return ans

n , m = map(int , list(raw_input().split()))
ans = fast_mod(3 , n , m)
ans = (ans - 1 + m) % m
print ans

n,m=map(long, raw_input().split())
ans=long(1)
mult=long(3)
while n:
    if n&1!=0:
        ans=(ans*mult)%m;
    mult=(mult**2)%m
    n/=2
if ans!=0:
    print long(ans-1)
else:
    print m-1

n,m = map(int,input().split())
# a = 2

def power(x, y, p) :
    res = 1     # Initialize result

    # Update x if it is more
    # than or equal to p
    x = x % p

    while (y > 0) :

        # If y is odd, multiply
        # x with result
        if ((y & 1) == 1) :
            res = (res * x) % p

        # y must be even now
        y = y >> 1      # y = y/2
        x = (x * x) % p

    return res
a = power(3,n,m)
print(a-1 if a!=0 else m-1)

n, m = map(int, raw_input().split())
print (pow(3,n,m)-1+m) % m

def pow_mod(x, y, z):
    number = 1
    while y:
        if y & 1:
            number = number * x % z
        y >>= 1
        x = x * x % z
    return number

n, m = map(int, raw_input().strip().split(' '))
print (pow_mod(3, n, m) - 1) % m

#coding=utf-8

def three_power_mod(n, MOD):
	p = 1
	t = 3
	while n != 0:
		if n % 2 != 0:
			p *= t
			p %= MOD
		t = (t*t)%MOD
		n /= 2
	return p

n,m = map(int, raw_input().split())
print (three_power_mod(n,m)+m-1)%m

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

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

print((fast_power(3, n) - 1 + m) % m)

n, m = map(int, input().split())
print((pow(3, n, m) - 1) % m)

a, b = map(int, input().split())
print((pow(3, a, b) + b - 1) % b)

n,m = map(int,raw_input().split())
print (pow(3,n,m) - 1)%m

n,m = map(int,input().split())
x = (pow(3,n,m)-1+m)%m
print(x)
#   C:\Users\Usuario\HOME2\Programacion\ACM

import sys

def get_ints(): return map(int, sys.stdin.readline().strip().split())

n,m = get_ints()
ans = (pow(3,n,m)-1+m)%m
print(ans)

n,m=map(int,input().split());print((pow(3,n,m)-1)%m)

# Made By Mostafa_Khaled

n, m = map(int, raw_input().split())
print (pow(3, n, m) - 1 + m) % m

import math

def powerk (a,x,y):
    if(x==1):
        return(a)
    elif(x<=0):
        return(1)
    else:
        if (a<=0):
            return(0)
        y0=math.ceil(math.log(y,a))
        if(y0<=0):
            return(a**x)
        if (x<y0):
            return((a**x)%y)
        t0=(a**y0)%y
        x_div_y0=x//y0
        t1=powerk(t0,x_div_y0,y)
        pow3_x_mod_y0=powerk(a,(x%y0),y)
        t2=t1*pow3_x_mod_y0
        return(t2)

def main():
    st=input().split(' ')
    x=int(st[0])
    y=int(st[1])

    t2=powerk(3,x,y)
    t3=(t2-1)%y

    print(t3)

main()

import fractions
def main():
	b,m=map(int , input().split());
	res=1
	h=3
	while b:
		if b%2:
			res=(res*h)%m
		h=(h*h)%m
		b=b//2
	res=res-1
	res=res%m
	print(res)
if __name__ == "__main__":
    main()

n, m = map(int, raw_input ().split ())
print (pow (3, n, m) - 1) % m

s = raw_input
n, m = map(int, s().split())
x = pow(3, n, m)-1
if x < 0: x+=m
x%=m
print x

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

def modular_expo(n, m):
    if n == 1:
        return 3
    if n == 0:
        return 1
    if n % 2 == 0:
        temp = modular_expo(n/2, m)
        return ((temp % m) * (temp % m)) % m
    else:
        return (3 * (modular_expo(n-1, m) % m)) % m

ans = modular_expo(n, m)
print (ans-1+m) % m

s = raw_input()
l = s.split()
n = int (l[0])
m = int (l[1])
tmp2 = 1
tmp = (3**1000000)%m
i = 1000000
sum = 0
while i>0:
    change = False
    while sum+i>n:
        change = True
        i//=10
    sum+=i
    if change:
        tmp = (3**i)%m
    tmp2*=tmp
print((tmp2-1)%m)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug  1 18:48:05 2020

@author: shailesh
"""

n,m = [int(i) for i in input().split()]

ans = pow(3,n,m) - 1

if ans == -1:
    ans = m-1

print(ans)

s = raw_input
n, m = map(int, s().split())
x = pow(3, n, m)-1
if x<0: x+=m
x%=m
print x

n,m=map(int,input().split())
x=pow(3,n-1,m)
ans=(x*2+x-1)%m
print(ans)

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)

n, m = map(int, input().split())
print((pow(3, n, m) - 1) % m)

#Test 2
import os
import sys
from io import BytesIO, IOBase

def binpow(a, b, m):
    if (not b): return 1
    if (b == 1): return a%m
    ret = binpow(a, b//2, m)
    ret = (ret * ret)%m
    if (b&1): ret = (ret * (a%m))%m
    return ret

def main():
    n,m = [int(c) for c in input().split()]
    ret = binpow(3, n, m)
    ret = (ret - 1)%m
    print(str(ret) + '\n')
    return 0

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# endregion

if __name__ == "__main__":
    main()

(n, m) = list(map(int, raw_input().strip().split()))
print((pow(3, n, m) - 1 + m) % m)

def binpow(a,n):
    res = 1
    while(n>0):
        if(n&1):
            res = (res*a)%m
        a = (a*a)%m
        n>>=1
    return res

n,m = map(int,input().split())
ans = binpow(3,n)-1
if(ans%m ==0 and ans != 0):
    print(m-1)
else:
    print(ans%m)

a, b = map(int,raw_input().split())
print (pow(3, a, b) + b - 1)% b

n, m = map(int, input().split())
def fast_pow(a, b):
    res, ret = a, 1
    while b > 0:
        if b % 2 == 1:
            ret = (ret * res) % m
        res = (res * res) % m
        b //= 2
    return ret % m
print((fast_pow(3, n) - 1) % m)

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

ans = 1
base = 3

while n != 0:
    if n & 1:
        ans = (ans * base) % m

    base = (base * base) % m
    n >>= 1

ans = (ans + m - 1) % m

print(ans)

n, m = map(int, raw_input().split())
print (pow(3, n, m) - 1 + m)%m

n,m = map(int,input().split())
x = (pow(3,n,m)-1+m)%m
print(x)
#   C:\Users\Usuario\HOME2\Programacion\ACM

a, b = map(int, input().split())
print((pow(3, a, b) + b - 1) % b)

#!/usr/bin/env python

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

bits = []
while n:
    bits = [n%2] + bits
    n /= 2

res = 1
tmp = 1
for b in bits[::-1]:
    tmp = (tmp**2 if tmp>1 else 3) % m
    if b:
        res = (res*tmp) % m

res = (res + m -1) % m

print res

#!/usr/bin/python3
N,M = [int(x) for x in input().strip().split()]
print((pow(3,N,M)-1)%M)

a, b = map(int, raw_input().split())
print((pow(3, a, b) + b - 1) % b)

def main():
    [n, m] = map(int, raw_input().split())
    print (pow(3, n, m)-1)%m

if __name__ == '__main__':
    main()

n, m = map(int, input().split())
print((pow(3, n, m) - 1) % m)

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

def mod_exp(a, b, n):
	x = a
	y = 1
	while b > 0:
		if b%2:
			y = (y*x)%n
		x = (x*x)%n
		b = b >> 1
	return y

print((mod_exp(3, n, m)-1)%m)

(n,m)= map(lambda x:int(x),raw_input().split())

def ppow(nn,kk,mm):
    if (kk==0):
        return 1;
    if (kk%2==0):
        tmp = ppow(nn,kk>>1,mm)
        return (tmp*tmp)%m
    else:
        tmp = ppow(nn,kk-1,mm)
        return (tmp*nn)%m
#    res = ppow(nn,kk>>1,mm);
#    res = res * res
#    res = res % mm
#    if (kk%2==0):
#        return res
#    else:
#        return ((res * nn)%mm)

res = 0
if n==1:
    print 2%m
else:
    res = ppow(3,n,m)
    res = res - 1
    res = res + m;
    res = res % m
    print res

a, b = map(int,raw_input().split())
print (pow(3, a, b) + b - 1)% b

def f(a, b):
    if b == 1:
        return a
    if b % 2 == 0:
        x = f(a, b // 2) % m
        return (x * x) % m
    else:
        return (f(a, b - 1) * a) % m

n, m = map(int, input().split())
print((f(3, n) - 1) % m)

n, m = (int(x) for x in input().split())
print((pow(3,n,m)-1)%m)

n,m=map(int,input().split())
x=pow(3,n-1,m)
ans=(x*2+x-1)%m
print(ans)

n, m = map(int, raw_input().split())
print (pow(3, n, m) - 1) % m

#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
#vsInput()

def bigmod(a,b,M):

    if(b==0):return 1

    if(b%2):
        return a%M * bigmod(a,b-1,M)
    else:
        ans=bigmod(a,b//2,M)
        return (ans*ans)%M

n,m=value()

ans=bigmod(3,n,m)

print((ans-1+m)%m)

def modPower(a, n, m):
    ret = 1
    while n > 0:
        if (n&1) == 1:
            ret = ret*a%m
        a = a*a%m
        n >>= 1
    return ret

def main():
    [n, m] = map(int, raw_input().split())
    print (modPower(3, n, m)+m-1)%m

if __name__ == '__main__':
    main()

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

r=pow(3,n,m)
r-=1
r+=m
r%=m

print(r)

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

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

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

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

n,m = map(int,raw_input().split())
print pow(3,n,m) - 1

def modPower(a, n, m):
    ret = 1
    while n > 0:
        if (n&1) == 1:
            ret = ret*a%m
        a = a*a%m
        n >>= 1
    return ret

def main():
    [n, m] = map(int, raw_input().split())
    print modPower(3, n, m)-1

if __name__ == '__main__':
    main()

import math
import time
from collections import defaultdict,deque
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
n,m=map(int,stdin.readline().split())
print((n*n*2)%m)

import sys

def get_ints(): return map(int, sys.stdin.readline().strip().split())

n,m = get_ints()
if n==1:
    print(2%m)
    exit()
ans = 0
for i in range(n):
    ans+=(n-1)*pow(3,i,m)
    ans%=m
print(ans)

import sys

def get_ints(): return map(int, sys.stdin.readline().strip().split())

n,m = get_ints()
ans = 0
for i in range(n):
    ans+=(n-1)*pow(3,i,m)
    ans%=m
print(ans)

n, m = map(int, input().split())
print(pow(3, n, m)  - 1)

n, m = (int(x) for x in input().split())
print(2 * pow(3,n-1,m))

(a,b) = map(lambda x:int(x),raw_input().split());
if a==1:
    print 2%b;
else:
    print (2*(3**(a-1)))%b

s = raw_input()
l = s.split()
n = int (l[0])
m = int (l[1])
tmp2 = 1
tmp = (3**1000000)%m
i = 1000000
sum = 0
while i>0:
    tmp2*=tmp
    change = False
    while sum+i>n:
        change = True
        i//=10
    sum+=i
    if change:
        tmp = (3**i)%m

print((tmp2-1)%m)

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

def exp(num,power):
	base = num
	pres = power
	ret = 1
	while(pres!=0):
		if(pres%2==1):
			ret = (ret*base)%m
		pres = pres/2
		base = (base*base)%m
	return ret

print exp(3,n)-1

n,m=map(int,raw_input().split())
x= pow(3,n,m) -1
if(x==-1):
    print m
else:
    print x

n,m=map(int,raw_input().split())
print pow(3,n,m) -1

s = raw_input
n, m = map(int, s().split())
print pow(5, n-1, m)+1

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

for i in range(n-1):
    a = a + (2*a)

print(a%m)

n,m = map(int,input().split())
# a = 2

def power(x, y, p) :
    res = 1     # Initialize result

    # Update x if it is more
    # than or equal to p
    x = x % p

    while (y > 0) :

        # If y is odd, multiply
        # x with result
        if ((y & 1) == 1) :
            res = (res * x) % p

        # y must be even now
        y = y >> 1      # y = y/2
        x = (x * x) % p

    return res

print(power(3,n,m)-1)

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

for i in range(n-1):
    a = 2 + (2*a)

print(a%m)

n, m = map(int, input().split())
print((5 * (n - 1)) % m)

n, m = map(int, input().split())
print(2 * n * n % m)

n,m  = map(int,input().split())
r = pow(3,n,m)
print(r-1)

n,m  = map(int,input().split())
r = pow(3,n,m)
if r < 0 :
    r += m
print(r-1)

n,m=map(long, raw_input().split())
ans=0
for i in range(n):
    ans+=2*pow(n,i,m)
print ans%m

(n,m)= map(lambda x:int(x),raw_input().split())

def ppow(nn,kk,mm):
    if (kk==0):
        return 1;
    if (kk%2==0):
        return (pow(nn,kk/2,mm)**2)%m
    else:
        return (pow(nn,kk-1,mm)*n)%m
#    res = ppow(nn,kk>>1,mm);
#    res = res * res
#    res = res % mm
#    if (kk%2==0):
#        return res
#    else:
#        return ((res * nn)%mm)

res = 0
if n==1:
    print 2%m
else:
    res = ppow(3,n,m)
    res = res - 1
    res = res + m;
    res = res % m
    print res

def modpow(a, b, n):
    if b == 0:
        return 1
    if b == 1:
        return a % n
    tmp = modpow(a, b // 2, n) % n
    tmp = (tmp * tmp) % n
    if tmp % 2 == 1:
        return (tmp * a) % n
    else:
        return tmp

def main():
    n, m = map(int, input().split())
    ans = (modpow(3, n, m) - 1) % m
    print(ans)

if __name__ == "__main__":
    main()

n,m = map(int,input().split())
i = n
ans = 0
while(i>1):
    ans += (2*i+1)*2
    i-=1
ans+=2
print(ans%m)

def binpow(a,n):
    res = 1
    while(n>0):
        if(n&1):
            res = (res*a)%m
        a = (a*a)%m
        n>>=1
    return res

n,m = map(int,input().split())
ans = binpow(3,n)-1
if(ans%m ==0):
    print(m-1)
else:
    print(ans%m)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug  1 18:48:05 2020

@author: shailesh
"""

n,m = [int(i) for i in input().split()]

ans = pow(3,n,m) - 1

if ans == -1:
    ans = m-1

print(m)

import sys
from math import *
from fractions import gcd
readints=lambda:map(int, input().strip('\n').split())

# ans: 3^n - 1

n,m=readints()

def pow3(n,m):
    res=1
    b=3

    while n>0:
        if n%2 == 1:
            res*=b
            res%=m
            n-=1
        else:
            b*=b
            b%=m
            n/=2
    return res

ans=pow3(n,m)-1
print(ans)

def fastpow(mod,times):
    if times==1:
        return 3
    else:
        if (times%2):
            now=fastpow(mod,(times-1)/2)%mod
            return (now*now*3)%mod
        else:
            now = fastpow(mod, (times ) / 2) % mod
            return (now * now ) % mod
n,m=map(int, input().split())
print(fastpow(m,n)%m-1)

def pow1(x, base):
    if base == 0:
        return 1
    sq = pow1(x, base // 2)
    sq = (sq * sq) % m

    if base % 2:
        sq *= x
    return sq

def sum_pow(r, n):
    return ((1 % m - pow1(r, n + 1) % m) % m) // (1 - r)

n, m = map(int, input().split())
print((2 * (sum_pow(3, n - 1) % m)) % m)

def pow1(x, base):
    if base == 0:
        return 1
    sq = pow1(x, base // 2)
    sq = (sq * sq) % m

    if base % 2:
        sq *= x
    return sq

def sum_pow(r, n):
    return (1 - pow1(r, n + 1)) // (1 - r)

n, m = map(int, input().split())
print((2 * sum_pow(3, n - 1)) % m)

'''input
3 8
'''
# practicing a skill right after sleep improves it a lot quickly
from sys import stdin, setrecursionlimit
import math

# main starts
n, m = list(map(int, stdin.readline().split()))
p = pow(3, n - 1, m)
print((2 * p) % m)

import math

def powerk (a,x,y):
    if(x==1):
        return(a)
    elif(x<=0):
        return(1)
    else:
        y0=math.ceil(math.log(y,a))
        if (x<y0):
            return((a**x)%y)
        t0=(a**y0)%y
        x_div_y0=x//y0
        t1=powerk(t0,x_div_y0,y)
        pow3_x_mod_y0=powerk(a,(x%y0),y)
        t2=t1*pow3_x_mod_y0
        return(t2)

def main():
    st=input().split(' ')
    x=int(st[0])
    y=int(st[1])
    print('x: ',x)
    print('y: ',y)

    t2=powerk(3,x,y)
    t3=(t2-1)%y

    print('t3: ',t3)

main()

st=input().split(' ')
x=int(st[0])
y=int(st[1])

mx=len(str(x))
if(mx>5):
    mx=5

m=1
for i in range(mx,-1,-1):
    print('i: ',i)
    fm=10**i
    fx=3**fm
    cr = x // fm
    x = x - cr*fm
    # m=m%y
    for j in range(cr):
        m=(m*fx)%y

res = m-1
print(res%y)

import math

def powerk (a,x,y):
    if(x==1):
        return(a)
    elif(x<=0 or a<=0):
        return(1)
    else:
        y0=math.ceil(math.log(y,a))
        if (x<y0):
            return((a**x)%y)
        t0=(a**y0)%y
        x_div_y0=x//y0
        t1=powerk(t0,x_div_y0,y)
        pow3_x_mod_y0=powerk(a,(x%y0),y)
        t2=t1*pow3_x_mod_y0
        return(t2)

def main():
    st=input().split(' ')
    x=int(st[0])
    y=int(st[1])

    t2=powerk(3,x,y)
    t3=(t2-1)%y

    print(t3)

main()

"""
Author    : co_devil Chirag Garg
Institute : JIIT
"""

from __future__ import division, print_function
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
# from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi
# from bisect import bisect_left,bisect_right
# from decimal import *,threading
"""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
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        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):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        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)
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')

def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), 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', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()

"""

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

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
dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1]
def getKey(item): return item[0]
def sort2(l): return sorted(l, key=getKey)
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 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
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')

graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000
def dfs(v, c):
    if visited[v]:
        if col[v] != c:
            print('-1')
            exit()
        return
    col[v] = c
    visited[v] = 1
    for i in graph[v]:
        dfs(i, c ^ 1)

def bfs(d,v):
    q=[]
    q.append(v)
    visited[v]=1
    while len(q)!=0:
        x=q[0]
        q.pop(0)
        for i in d[x]:
            if visited[i]!=1:
                visited[i]=1
                q.append(i)
        print(x)
def make_graph():
    d={}
    v,e=mi()
    for i in range(e):
        x,y=mi()
        if x not in d.keys():
            d[x]=[y]
        else:
            d[x].append(y)
        if y not in d.keys():
            d[y] = [x]
        else:
            d[y].append(x)
    return d
def gr2(l,n):
    d={}
    for i in range(1,n+1):
        if i not in d.keys():
            d[i]=l[i]
        else:
            d[i].append(l[i])
    return d

n,m=mi()
print(powerMod(3,n,m)-1)

"""
Author    : co_devil Chirag Garg
Institute : JIIT
"""

from __future__ import division, print_function
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
# from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi
# from bisect import bisect_left,bisect_right
# from decimal import *,threading
"""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
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        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):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        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)
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')

def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), 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', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()

"""

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

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
dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1]
def getKey(item): return item[0]
def sort2(l): return sorted(l, key=getKey)
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 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
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')

graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000
def dfs(v, c):
    if visited[v]:
        if col[v] != c:
            print('-1')
            exit()
        return
    col[v] = c
    visited[v] = 1
    for i in graph[v]:
        dfs(i, c ^ 1)

def bfs(d,v):
    q=[]
    q.append(v)
    visited[v]=1
    while len(q)!=0:
        x=q[0]
        q.pop(0)
        for i in d[x]:
            if visited[i]!=1:
                visited[i]=1
                q.append(i)
        print(x)
def make_graph():
    d={}
    v,e=mi()
    for i in range(e):
        x,y=mi()
        if x not in d.keys():
            d[x]=[y]
        else:
            d[x].append(y)
        if y not in d.keys():
            d[y] = [x]
        else:
            d[y].append(x)
    return d
def gr2(l,n):
    d={}
    for i in range(1,n+1):
        if i not in d.keys():
            d[i]=l[i]
        else:
            d[i].append(l[i])
    return d

n,m=mi()
if powerMod(3,n,m)-1>0:
    print(powerMod(3,n,m)-1)
else:
    print(m+powerMod(3,n,m)-1)

"""
Author    : co_devil Chirag Garg
Institute : JIIT
"""

from __future__ import division, print_function
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
# from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi
# from bisect import bisect_left,bisect_right
# from decimal import *,threading
"""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
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        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):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        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)
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')

def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), 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', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()

"""

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

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
dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1]
def getKey(item): return item[0]
def sort2(l): return sorted(l, key=getKey)
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 powerMod(x, y, p):
    res = 1
    x %= p
    while y > 0:
        if y & 1:
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p1
    return res
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')

graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000
def dfs(v, c):
    if visited[v]:
        if col[v] != c:
            print('-1')
            exit()
        return
    col[v] = c
    visited[v] = 1
    for i in graph[v]:
        dfs(i, c ^ 1)

def bfs(d,v):
    q=[]
    q.append(v)
    visited[v]=1
    while len(q)!=0:
        x=q[0]
        q.pop(0)
        for i in d[x]:
            if visited[i]!=1:
                visited[i]=1
                q.append(i)
        print(x)
def make_graph():
    d={}
    v,e=mi()
    for i in range(e):
        x,y=mi()
        if x not in d.keys():
            d[x]=[y]
        else:
            d[x].append(y)
        if y not in d.keys():
            d[y] = [x]
        else:
            d[y].append(x)
    return d
def gr2(l,n):
    d={}
    for i in range(1,n+1):
        if i not in d.keys():
            d[i]=l[i]
        else:
            d[i].append(l[i])
    return d

n,m=mi()
x=12*n-10
print(x%m)

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

print((4 * pow(2, n, m) - 6) % m)

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

ans = pow(3, n, m)

if n % 2 == 1:
    ans -= 1
else:
    ans += 1

print(ans % m)

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

def mod_exp(a, b, n):
	x = a
	y = 1
	while b > 0:
		if b%2:
			y = (y*x)%n
		x = (x*x)%n
		b = b >> 1
	return y

print(mod_exp(3, n, m)-1)

n, m = map(int, input().split())
print((n**3-1)%m)


A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?

The first line contains three positive integers k, n, w (1  ≤  k, w  ≤  1000, 0 ≤ n ≤ 109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.

Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.

k,n,w = input().split()
k,n,w = int(k), int(n), int(w)
s = (w*(w+1)/2)*k
res = n-s
if res>0:
    print(0)
else:
    print(int(abs(res)))

"""
Input = 3 17 4

Output = 13
"""
k, n, w = raw_input().split(' ')
k = int(k)
n = int(n)
w = int(w)
calculated_sum = (((((w * (w - 1)) / 2) + w) * k) )
if calculated_sum < n:
	amount_the_soldier_has_to_borrow = 0
else:
	amount_the_soldier_has_to_borrow = calculated_sum - n
print amount_the_soldier_has_to_borrow

def solve(k, n, w):

    totalMoneyNeeded = ((w*(w+1)) * k)/2
    return max(totalMoneyNeeded - n, 0)

if __name__ == "__main__":
    inputs = raw_input().split(" ")
    print solve(int(inputs[0]), int(inputs[1]), int(inputs[2]))

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def MI(): return map(int, sys.stdin.readline().strip().split())
def LI(): return list(map(int, sys.stdin.readline().strip().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines().strip()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().strip().split()]
def LF(): return [float(x) for x in sys.stdin.readline().strip().split()]
def LS(): return sys.stdin.readline().strip().split()
def I(): return int(sys.stdin.readline().strip())
def F(): return float(sys.stdin.readline().strip())
def S(): return sys.stdin.readline().strip()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

from math import factorial,gcd
from random import choice,randint
from sys import stdin,stdout
inp=stdin.readline
out=stdout.write

k,n,w=MI()
p=k*((w*(w+1))//2)
if p>n:
    print(p-n)
else:
    print(0)

q=input().split()
a=int(q[0])
b=int(q[1])
c=int(q[2])
i=1
s=0
while i<=c:
  s+=a*i
  i+=1
if b>=s:
  print(0)
else:
  print(s-b)

initial, money, to_buy = list(map(int, input().split(' ')))
sum = 0
total = 0
for i in range(1, to_buy+1):
    to_pay = initial * i
    if to_pay > money:
        sum += to_pay - money
        money -= money

    else:

        rem = money - to_pay
        money = rem

print(sum)

k,n,w = [int(i) for i in input().split()]
total = 0
for i in range(1,w+1):
    total = total + (i * k)

borrow = n-total
if borrow >= 0:
    print(0)
else:
    print(abs(borrow))

data_k_n_w = input().split(' ')
data_k_n_w = [int(i) for i in data_k_n_w]

amount = int(data_k_n_w[0]*((data_k_n_w[2]*(data_k_n_w[2]+1))/2))

if amount < data_k_n_w[1]:
    print(0)
else:
    print(abs(amount-data_k_n_w[1]))

k , n , w = list(map(int , input().split(" ")))
cost = 0
for i in range(1,w+1):
    cost += i*k
if cost-n < 0:
    print(0)
else:
    print(cost-n)

inputs = input().split()
cost_bannana = int(inputs[0])
amount_soldier = int(inputs[1])
no_of_bananas = int(inputs[2])

total_cost = cost_bannana * (no_of_bananas)*(no_of_bananas + 1) // 2
borrow = total_cost - amount_soldier
if borrow > 0:
    print(borrow)
else:
    print(0)

k, n, w = map(int, input().split())
cena = 0
for i in range(w):
    cena += k * (i+1)
if cena >= n:
    print(cena - n)
else:
    print(0)

var1,var2,var3=map(int,input().split(" "))

if var3!=0:
    x =0
    for i in range(1,var3+1):
        x = x+ var1*i
    v = x - var2
    if v>0:
        print(v)
    else:
        print(0)
else:
    print(0)

k,n,w=map(int,input().split())
j=0
for i in range(1,w+1):
    j=j+i*k
if j>n:
    print(j-n)
else:
    print(0)

#!/usr/bin/env Python3
x = input()
k,n,w = x.split(" ")

k = int(k)
n = int(n)
w = int(w)
total = 0

while(w != 0):
        total += (k*w)
        w -=1

borrow = total-n

if(borrow >= 0):
	print(borrow)
else:
	print(0)

from math import *
k, n, w = map(int, input().split())
print(max(0,w*(w+1)*k//2-n))

#!/usr/bin/env python

import sys

def bananas(cost, amnt, num):
  total = 0
  for i in range(num):
    total += (i + 1) * cost
  print total - amnt if total > amnt else 0

if __name__ == '__main__':
  cost, amnt, num = (int(x) for x in sys.stdin.readline().split())
  #cost, amnt, num = (3, 17, 4)
  bananas(cost, amnt, num)

k,n,w=map(int,input().split())
tot=0
for i in range(w):
    tot+=(i+1)*k
if n>=tot:
    print(0)
else:
    print(tot-n)

x,y,z=map(int,input().split())
sum=0
for i in range(1,z+1):
    sum=sum+i*x
if sum<y:
    print(0)
else:
    print(sum-y)

k,n,w=map(int,input().split())
if (sum(list(range(1,w+1)))*k) > n:
    print((sum(list(range(1,w+1)))*k)-n)
else:
    print("0")

k,n,w=[int(x) for x in input().split()]

def fun(k,n,w):
    sum=0
    for i in range(1,w+1):
        sum+=i*k
    ans=sum-n
    if ans>0:
        return print(ans)
    else: return print(0)
fun(k,n,w)

k, n, w=map(int, input().split())
s=0
for i in range(1,w+1):
           s=s+(i*k)
a=s-n
if s==n or s<n:
           print("0")
else:
           print(a)

#coding=UTF-8
# (ˊ・ω・ˋ)
from math import *
from heapq import *
PI = acos(-1)
k, w, n = map(int, raw_input().strip().split(' '))
m = k*(n+1)*n/2
if m > w:
    print m - w
else:
    print 0

k,n,w = map(int,input().split())
s = 0;
for i in range(1,w+1):
    s += (i*k)
if n >= s:
    print("0")
else:
    print(s - n)

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

x = sum([k*i for i in range(w+1)])

if n > x:
    print(0)
else:
    print(x - n)

x = raw_input()
m = 0
y = x.split(" ")
k = int(y[0])
n = int(y[1])
w = int(y[2])
p = int(1)
l = int(0)
for i in range(w+1):
  if i >  0:
    p = i*k
    l += p
m = l - n
if m >= 0:
  print m
else:
  print "0"

k, n, w = map(int, raw_input().split())
amount = 0
for a in range(1, w+1):
	amount += (a * k)
answer = amount - n
if answer < 0:
	answer = 0
print answer

k,n,w = map(int,raw_input().split())
for i in range(1,w+1):
    n = n - (i*k)
if n>0:
    print "0"
else :
    print abs(n)

k,n,w=list(map(int,input().split()))
if k*(1+w)*w//2-n<=0:
    print(0)
else:
    print(k*(1+w)*w//2-n)

a=input().split()
k,n,w=a
k=int(k)
n=int(n)
w=int(w)
total_price=0
for i in range(0,w+1):
    total_price=total_price+i*k
if n>total_price:
    borrow_money=0
else:
    borrow_money=total_price-n

print(borrow_money)

input = input().split(" ")

k = int(input[0]) # k is the price of ea banana
n = int(input[1]) # n is the user's money
w = int(input[2]) # w is number of bananas
z = []

for i in range(1, w + 1):
	z.append(i * k)
total = sum(z)
borrow = sum(z) - int(input[1])

if n > total:
	print(0)
else:
	print(borrow)

k, n, w = map(int, input().split())
#cost = 0
#for i in range (1,w+1) :
#    a = i*k
#    cost += a
#print(int(cost - int(n)))

print(max(0, k*w*(w+1)//2 - n))

val=list(map(int,input().split(' ')))
ans=0
for i in range(val[2]):
    ans=ans+((i+1)*val[0])
if(val[1]<ans):
    print(abs(val[1]-ans))
else:
    print(0)

k, d, n=map(int, input().split())
# d=int(input())
# n=int(input())
i=1
sum=0
while(i<=n):
    sum=sum + (k*i)
    i=i+1

if(sum <= d):
    print(0)

else:
    print(sum-d)

k, n, w = map(int, raw_input().split())
print max(k*w*(w+1)/2 - n, 0)

c = input()
c = c.split()
a = 0
for i in range(1, int(c[2]) + 1, 1):
    a += i * int(c[0])
if a > int(c[1]):
    print(a - int(c[1]))
else:
    print(0)

first, money, n_ban = [int(u) for u in input().split()]
money_r = first*((n_ban*(n_ban+1))//2)
if money > money_r:
	print('0')
else:
	print(money_r-money)

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

p=k*((w*(w+1))//2)
if p>n:
    print(p-n)
else:
    print(0)

"""
Author    : raj1307
Institute : Jalpaiguri Government Engineering College
Date      : 22.03.19
"""
from __future__ import division, print_function
import itertools,os,sys
#from collections import deque, Counter, OrderedDict
#from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect_left,bisect_right
#from decimal import *
from atexit import register
from io import BytesIO, StringIO

if sys.version_info[0]<3:
    range = xrange
    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
    sys.stdout = BytesIO()
    register(lambda: os.write(1, sys.stdout.getvalue()))
else:
    sys.stdin = StringIO(os.read(0, os.fstat(0).st_size).decode())
    sys.stdout = StringIO()
    register(lambda: os.write(1, sys.stdout.getvalue().encode()))

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

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

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}
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,num):return [[num for x in range(n)] for y in range(n)]
def ntl(n):return [int(i) for i in str(n)]
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 main():
    k,n,w=mi()
    if int((w*(w+1))/2)*k<=n:
        print(0)
    else:
        print(int((w*(w+1))/2)*k-n)

if __name__ == "__main__":
    main()

a=[int(i) for i in input().split()]
intialcost=a[0]
money=a[1]
banana=a[2]
n=int(banana)+1
total=0
final=0
for i in range(n):
    total=total+i*int(intialcost)
if total<=money:
    final=0
else:
    final=total-int(money)
print(final)

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

print max(k*w*(w+1)/2 -n,0)

n,k,w=map(int,input().split())
sum=0
for i in range(1,w+1):
    sum=sum+(n*i)
if sum>k:
    print(sum-k)
elif sum<=k:
    print("0")

k, n, w = [int(i) for i in raw_input().split()]
ans = (w*(w+1)*k)/2 - n
if ans >= 0:
	print(ans)
else:
	print(0)

k, n, w = map(int, input().split())
s = (k + w*k)/2*w
if s > n:
    print(int(s - n))
else:
    print(0)

values = raw_input().split()

cost_banana = int(values[0])
dollars = int(values[1])
banana = int(values[2])

counter = 1
cost = 0

while counter < banana + 1:
    cost += cost_banana * counter
    counter += 1

if cost - dollars < 0:
    print(0)
else:
    print(cost - dollars)

def solver(k,n,w):
    tot=(w/2)*((2*k)+((w-1)*k))
    # print(tot)
    if (n - int(tot)) >= 0:
        return 0
    return int(tot) - n

if __name__=='__main__':
    a,b,c=map(int,input().split())
    print(solver(a,b,c))

k, n, w = map(int, input().split())
cost = int((w/2)*(2*k+(w-1)*k)-n)
if cost < 0:
    print(0)
else:
    print(cost)

k , n , w = input().split()
k = int(k)
n = int(n)
w = int(w)
x = 0
s = 1
for i in range (w):
    x = x + (s*k)
    s = s + 1
if x > n :
    print ( x - n )
else :
    print (0)

k, n, w = map(int, raw_input().split())
b = (k * (w * (w + 1)) / 2) - n
print max(0, b)

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

result = ( arr[0] * ((arr[2] * (arr[2] + 1) / 2)) - arr[1] )

if result < 0:
	print "0"
else:
	print result

k1,n1,m1=raw_input().split()
k=int(k1)
n=int(n1)
m=int(m1)
#print k,n,m
j=0
for i in range(1,m+1):
    j+=k*i
    #print j
total=j-n
print max(total,0)

s=raw_input()
a,b,c=s.split()
total=0
tot=0
a1=int(a)
b1=int(b)
c1=int(c)
total1=int(total)
tot1=tot
for i in range(1,int(c1)+1):
    tot1=(a1*i)+tot1

#print tot1
total1=(tot1)-(b1)
#print total1
if total1>0:
    print(total1)
else:
    print(0)

num = raw_input().split(" ")
n = int(num[2])
m = int(num[0])
tot = 0

while n!=0:
	tot = tot + m * n
	n = n-1
var = tot - int(num[1])

if var<0:
	print(0)
else:
	print(var)

nums = map(int, raw_input().split())
print max((nums[2]*(nums[2]+1))/2 * nums[0] - nums[1], 0)

x, y, z = raw_input().split()
banana_price = int (x)
pocket_money = int (y)
number_of_bananas = int (z)
total_price = 0

for x in range(1, number_of_bananas + 1):
    total_price += (x * banana_price)

money_to_borrow = total_price - pocket_money

if money_to_borrow <= 0:
    money_to_borrow = 0

print(money_to_borrow)

k,n,w=input().split()
k=int(k)
n=int(n)
w=int(w)
t=int(w*(w+1)*k/2)
if(t>n):
    print(t-n)
else:
    print("0")

lists = list(map(int, input().rstrip().split()))

for i in range(1, lists[2]+1):
    lists[1] -= i*lists[0]

if lists[1] >= 0:
    print(0)
else:
    print(abs(lists[1]))

k, n, w = [ float(x) for x in raw_input().split() ]

amount = (w*(w+1)/2.0)*k
if amount<n:
    print 0
else:
    print int(amount-n)

import sys

#http://codeforces.com/problemset/problem/546/A

k, n, w = map(int, sys.stdin.readline().split())

i = 1
while i<=w:
    pay = i*k
    n = n-pay
    i+=1

if n<0:
    print abs(n)
else:
    print 0

a = list(map(int,input().split()))
sum = int(a[0]*(a[2]*(a[2]+1)/2))
if sum > a[1]:
    print(sum - a[1])
else:
    print("0")

banana_1, money, bananas = map(int, input().split())
cost = 0
for num_banana in range(1, bananas + 1):
    cost += banana_1 * num_banana
debt = money - cost
if(debt < 0):
    print(abs(debt))
else:
    print("0")
#Done

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

c = 0
for i in range(1, x[2]+1):
    c+=x[0]*i

if(x[1]>=c):
    print("0")
else:
    print(c-x[1])

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

s=sum(range(1,w+1))*k

if s-n>0:
    print(s-n)
else:
    print(0)

k,n,w = map(int, input().split(" "));x = 0
for i in range(1,w+1): x += i*k
print(abs(n-x)) if(x>n) else print("0")

def banana(s):
    l = map(float, s)
    k = l[0]
    n = int(l[1])
    w = l[2]
    need = ((w/2) * ((2*k)+((w-1)*k)))
    need = int(need)
    if (n>=need):
        print 0
    else:
        print (need - n)
s = raw_input().split()
banana(s)

input=raw_input()

input_arr=input.split(" ")

k=int(input_arr[0])

n=int(input_arr[1])
w=int(input_arr[2])

i=0

total=0

while i<w:
    i+=1
    total+= k*i
if n>=total:
    print(0)
else:
    print(total-n)

k,n,w=map(int,input().rstrip().split())
sum=(w)*(w+1)
l=sum//2
new=l*k
if new<n:
    print(0)
else:
    print(new-n)

# k = int(input())
# w = int(input())
# n = int(input())
k, w, n = [int(x) for x in input().split()]
ans = k * n * (n + 1) // 2 - w
if ans < 0:
    ans = 0
print(ans)

k, n, w = map(int, input().split())
cst = 0

for i in range(w):
    cst += (i + 1) * k

if cst - n > 0:
    print(cst - n)

else:
    print("0")

k,n,w = map(int,input().split())
s = (w/2)*(2*k+(w-1)*k)

if s<=n:
    print("0")
else:
    print("{:.0f}".format(s - n))

k,n,w=map(int,input().split())
tong=0
for i in range(w):
	tong+=(i+1)*k
if tong - n < 0 : print(0)
else: print(tong-n)

k,n,w=map(int,input().split())
t=0
for i in range(1,w+1):
  t=t+i*k
a=t-n
if a<0:
  a=0
print(a)

from math import ceil
import sys,bisect,copyreg,copy,statistics,os
def inp(): return sys.stdin.readline().strip()
def IIX(): return (int(x) for x in sys.stdin.readline().split())
def II(): return (int(inp()))
def LI(): return list(map(int, inp().split()))
def L(x):return list(x)
def out(var): return sys.stdout.write(str(var))

k, n, w=IIX()

cost=k*((w*(w+1)//2))

if cost-n>=0:
    out(cost-n)
else:
    out(0)

st=raw_input()
l=st.split()
k=int(l[0])
n=int(l[1])
w=int(l[2])
###i,j = raw_input("Enter two values:  ").split
##i = int(i)
##j = int(j)
req=k*((w*(w+1))/2)
if (req-n)>=0:
    print req-n
else:
    print "0"

k,n,w = map(int, raw_input().split())
res = k*(w*(w+1)/2)
print (res - n)*(res > n)

k,n,w=raw_input().split()
k=int(k);n=int(n);w=int(w)
s=w*(w+1)*k/2-n
if s<=0:
    print 0
else:
    print s

k, n, w = map(int,input().split())
sum = 0
for i in range(1, w+1):
    s = k * i
    sum = s + sum
if sum - n> 0:
    print(sum - n)
else:
    print("0")

def solve(k, n, w):

    moneyreq = ((w*(w+1)) * k)/2
    return max(moneyreq - n, 0)

if __name__ == "__main__":
    inputs = raw_input().split(" ")
    print solve(int(inputs[0]), int(inputs[1]), int(inputs[2]))

def soilder(k,n,w):
    if type(k) is not int or type(n) is not int or type(w) is not int:
        raise TypeError("Arguments are not number")

    if k <0 or n < 0 or w <0:
        raise ValueError("All numbers must be integer")

    price = w*(w+1)*k/2

    if price > n:
        return price - n
    else:
        return 0

(k,n,w) = raw_input("").split(" ")
print soilder(int(k),int(n),int(w))

k,n,w=map(int,input().split())
c=0
for i in range(1,w+1):
    c+=k*i

x=c

if x<=n:
    print(0)
else:
    print(x-n)

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

#k,n,w = 3,17,4

price = 0
for i in xrange(1, w+1):
    price += i*k
if w == 0:
    print 0
else:
    print (price-n) if price > n else 0

k,n,w  = [int(i) for i in raw_input().split(" ")]

s = 0
for i in xrange(w):
    s += (i + 1) * k

if s <= n: print 0
else: print s-n

c = input()
c = c.split()
a = 0
for i in range(1, int(c[2]) + 1, 1):
    a += i * int(c[0])
if a > int(c[1]):
    print(a - int(c[1]))
else:
    print(0)

import math

k, n, w = [float(x) for x in raw_input().split()]

a = int (k*(w*(w+1))/2 - n)

if a<0:
	print '0'
else:
	print a

val=list(map(int,input().split(' ')))
ans=0
for i in range(val[2]):
    ans=ans+((i+1)*val[0])
if(val[1]<ans):
    print(abs(val[1]-ans))
else:
    print(0)

k,n,w=map(int,raw_input().split())
if 1<=k<=1000 and 1<=w<=1000 and 0<=n<=10**9:
    totalcost=0
    borrow=0
    for i in range(1,w+1):
        totalcost+=i*k
    if(totalcost>n):
        borrow=totalcost-n
    print borrow

k, n, w = map(int, input().split())
cena = 0
for i in range(w):
    cena += k * (i+1)
if cena >= n:
    print(cena - n)
else:
    print(0)

a=raw_input().split()
k=int(a[0])
n=int(a[1])
w=int(a[2])
w=w*(w+1)/2
d=w*k-n
if d<0:
    d=0
print d

k , n , w = input().split()
k = int(k)
n = int(n)
w = int(w)
x = 0
for i in range ( 1 , (w+1) ):
    x = x + (i*k)
if x > n :
    print ( x - n )
else :
    print ( n - x )

k,n,w=map(int,input().split())
tong=0
for i in range(w):
	tong+=(i+1)*k
if tong < 0 : print(0)
else: print(tong-n)

k,n,w = map(int,raw_input().split())
if k ==w and k <n:
    print "0"
    exit()
for i in range(1,w+1):
    n = n - (i*k)
print abs(n)

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

total = 0

for i in range(w):
    total = total + k*(i+1)

print(total)

if(total == n-1):
    print(total)
else:
    print(total - n)

a,b,c = map(int,input().split())
j = 1
l = 0
if b % 2 != 0:
    for i in range(1,c+1):
        j += i * a
    print(j - b)
else:
    for u in range(1,c+1):
        l += u * a
    print(j - b)

import math
k, n, w = map(int, input().split())
x=int()
while k>=1 and n>=0:
    x = (k+w*k)/2*w
    print(abs(x-n))
    break

n, k, w = map(int, input().split())
print(n - ((w * (w + 1)) / 2) * k)

k,n,w = map(int,input().split(" "))
total = (w + 2*k)*k
if (n>total):
    print('0')
else:
    print(total - n)

k, n, w = map(int, input().split())
t = ((w+1) * w * k) // 2
print(t - n)

x, y, z = map(int, input().split())
if z >= y:
    print(0)
else:
    print(y-z)

k,n,w=map(int,input().rstrip().split())
w=(w)*(w+1)
w=w//2
new=w*k
if n>w:
    print(0)
else:
    print(w-n)

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

s = int(k*(w*(w+1)/2) - n)

if s < 0:
    print(s)
else:
    print("0")

k,n,w = map(int, raw_input().split()) #bananas, $$, bananas wanted
tot=0

for i in range(1,w+1):
	tot+=i

cost = tot*k
borrow = abs(n-cost)

print borrow
#3+6+9+12 = 30-17=13

k,n,w = input().split()
k,n,w = int(k), int(n), int(w)
s = (w*(w+1)/2)*k
res = n-s
if res>0:
    print(0)
else:
    print(res)

k,n,w = map(int,input().split(" "))
required = ((w*(w+1))//2)*k
print(n-required)

def solver(k,n,w):
    tot=(w//2)*((2*k)+((w-1)*k))
    return tot - n

if __name__=='__main__':
    a,b,c=map(int,input().split())
    print(solver(a,b,c))

# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 16:27:18 2020

@author: A2B
"""

summ,i=0,0
k,n,w=map(int,input().split())
for i in range(w+1):
    summ+=(i*k)

print(summ-n)

knw=input().split()
k=int(knw[0])
n=int(knw[1])
w=int(knw[2])
costo=0
for i in range(1,w+1):
    costo=costo+k*i
print(abs(n-costo))

a=raw_input().split()
k=int(a[0])
n=int(a[1])
w=int(a[2])
w=w*(w+1)/2
print w*k-n

k,n,w=map(int,input().rstrip().split())
w=(w)*(w+1)
w=w//2
new=w*k
if new>w:
    print(0)
else:
    print(w-new)

n = raw_input().split(' ')
cost = int(n[0])
num = int(n[2])
avail = int(n[1])

print cost*(num*(num+1)/2) - avail

def cn(v):
	k,s,n=v
	print(v)
	return k*n*(n+1)//2-s

print(cn([int(x) for x in input().split()]))

a = str(input())
a = a.split(' ')
k = int(a[0])
n = int(a[1])
w = int(a[2])
x = int(0)
i = 1
for i in range(w-n):
    x += k*i

if x <= n:
    print(0)
    exit()
if x > n:
    x -= n
    print(x)

banana_1, money, bananas = map(int, input().split())
cost = 0
for num_banana in range(1, bananas + 1):
    cost += banana_1 * num_banana
debt = cost - money
print(debt)

[k, n, w] = [int(_) for _ in input().split()]

print( max(0, k*w*(w-1)//2-n) )

from sys import stdin,stdout
from collections import Counter
from math import ceil
from bisect import bisect_left
from bisect import bisect_right
import math

def ai(): return list(map(int, stdin.readline().split()))
def ei(): return map(int, stdin.readline().split())
def ip(): return  int(stdin.readline().strip())
def op(ans): return stdout.write(str(ans) + '\n')

k,n,w=ei()
s=0
for i in range(w):
    s+=k*i
print(s-n)

k,n,w = map(int,input().split())
totalsum = k*(w*(w+1)/2)
print(totalsum-n)

k, n, w=map(int, input().split())
s=0
for i in range(1,w+1):
           s=s+(i*k)
a=s-n
print(a)

k, n, w = list(map(int, input().split()))
count = 0
sum = (w*(w-1)*k)/2
if sum - n < 0:
    print("0")
else:
    print(sum - n)

k1,n1,w1=input().split()
k=int(k1)
n=int(n1)
w=int(w1)
mused=0
count=1
p=0
i=w
while i>0:
    if mused<=n:
        mused=count*k+mused
        count=count+1
        i=i-1
    else:
        mused=count*k+mused
        p=mused-n
        i=i-1
print(p)

import sys

local_launch = False
try:
    open('LOCAL').read()
    local_launch = True
except:
    pass
input_data = open('INPUT.txt').read() if local_launch else sys.stdin.read()
done = {'i': 0}
tokens = input_data.split()

def next_token():
    result = tokens[done['i']]
    done['i'] += 1
    return result

def next_int():
    return int(next_token())

def next_str():
    return next_token()

############## BEGIN OF CODE #####################

k = next_int()
n = next_int()
w = next_int()
a = 1
i = 1
while i != w:
    i = i + 1
    a=a+i
    u  = a  * k
if u - n < 0:
    print(u - n)
else:
    print(0)

# а как сделать чтобы сдлеть k*2k*3k... то сделать w раз

#а=1
#i=1
#До тех пор пока i не равно 100 делаем:
 #   i=i+1
#    a=a+i
#стоимость банана(на сколько у нас бананов тоесть например 3 значит 1+2+3)

############# END OF CODE #####################

import sys
temp = sys.stdin.readline()

while temp:

    k, n, w = temp.split(" ")
    k = int(k)
    n = int(n)
    w = int(w)

    aux = ((w)*(w+1))* k/2
    if aux - n < 0:
        print(0)
    else:
        print(aux - n)
    temp = sys.stdin.readline()

k,n,w=input().split()
k=int(w)
n=int(k)
w=int(n)
sum=0
for i in range(k):
    sum+=w*i
print(sum-n)

x=0
k,n,w=input().split()
k=int(k)
n=int(n)
w=int(w)
for o in range(1,w+1):
    x=k*o+x
m=x-n
if m<0:
    m==m+(m*-1)
print(m)

a,b,c=map(int,input().split())
x=a*(b*(b+1))/2
if (x-c)>0:
	print(x-c)
else:
	print("0")

T=list(map(int,input().split(' ')))
k=T[0]
n=T[1]
w=T[2]

A=w*(w+1)/2
PA=A*k
print(round(PA-n))

"""n = int(input())
count = 0
for i in range(n):
	c = 0
	p = [int(k) for k in input().split()]
	for j in p:
		if j == 1:
			c+=1
	if c >=2:
		count+=1
print(count)"""
"""n,k = input().split()
count = 0
scores = [int(i) for i in input().split()]
kth = scores[int(k)-1]
for j in scores:
	if j == 0:
		continue
	elif j>=kth:
		count += 1
print(count)"""
"""word = input()
vowel = ['a','e','i','o','u','y','A','E','I','O','U','Y']
for i in word:
	if i in vowel:
		continue
	elif i not in vowel:
		print('.'+i.lower(),end = '')"""
"""import math
m,n = input().split()
print(math.floor((int(m)*int(n))/2))"""
"""n = int(input())
x = 0
for i in range(n):
	lis = []
	lis = input()
	if (lis[0] == '+'and lis[1]=='+') or (lis[1] == '+' and lis[2] == '+'):
		x += 1
	elif (lis[0] == '-'and lis[1]=='-') or (lis[1] == '-' and lis[2] == '-'):
		x -= 1
print(x)"""
"""s = input()
a = s[0].capitalize()
print(a+s[1:])"""
"""Petya and strings
n1 = input()
n2 = input()
c = 0
for i in range(len(n1)):
	if ord(n1[i].lower()) > ord(n2[i].lower()):
		print(1)
		c = 1
		break
	elif ord(n1[i].lower()) < ord(n2[i].lower()):
		print(-1)
		c = 1
		break
	else:
		continue
if c == 0:
	print(0)"""
"""beautiful matrix
for i in range(5):
	a =[]
	for j in input().split():
		a.append(int(j))
	if 1 in a:
		print(abs(a.index(1)-2)+abs(i-2))"""
"""helpful maths
n = [int(i) for i in input().split('+')]
n.sort()
for i in range(len(n)):
	if i != len(n)-1:
		print(n[i],end='+')
	else:
		print(n[i])"""
"""football
n = input()
if '0000000' in n:
	print('YES')
elif '1111111' in n:
	print("YES")
else:
	print('NO')"""
"""stones on the table
n = int(input())
rock = input()
c = 0
for i in range(n-1):
	if rock[i] == rock[i+1]:
		c += 1
print(c)"""
"""boy or girl
n = input()
c = 0
for i in range(len(n)):
	if i == 0:
		c+=1
	elif n[i] not in n[:i]:
		c+=1
if c%2 == 0:
	print("CHAT WITH HER!")
else:
	print("IGNORE HIM!")"""
"""Young physicist
n = int(input())
x1=y1=z1=0
for i in range(n):
	x,y,z=input().split()
	x1=x1+int(x)
	y1=y1+int(y)
	z1=z1+int(z)
if x1==0 and y1==0 and z1==0:
	print("YES")
else:
	print("NO")"""
"""soldier and banana"""
k,n,w=input().split()
money = 0
for i in range(1,int(w)+1):
	money += int(k)*i
if int(n)>money:
	print(money)
else:
	print(abs(money-int(n)))

first, money, n_ban = [int(u) for u in input().split()]
money_r = first*((n_ban*(n_ban+1))//2)
if first > money_r:
	print('0')
else:
	print(money_r-first)

c = input()
c = c.split()
a = 0
for i in range(1, int(c[2])+1, 1):
    a += i*int(c[0])
print(a-int(c[1]))

k,n,w=map(int,raw_input().split())
sum=0
for i in range(1,w+1):
  sum=sum+i*k
borrow=sum-n
print borrow

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

t = c * (n*(n + 1)) // 2
print(t - a)

initial, money, to_buy = list(map(int, input().split(' ')))
sum = 0
total = 0
for i in range(1, to_buy+1):
    if initial > money:
        sum += initial * i

    else:
        pay = i * initial
        rem = money - pay
        money = rem

sum -= money
print(sum)

k, n, w = map(int, input().split())
#cost = 0
#for i in range (1,w+1) :
#    a = i*k
#    cost += a
#print(int(cost - int(n)))

print(max(0, k*w*(w+1)/2) - n)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#   Soldier and Bananas.py
#
#  Copyright 2020 Rahul <Rahul@DESKTOP-02JFRKS>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

cost, amount, banana = map(int, input().split())
cst = 0
for i in range(1,banana+1):
	cst += i*cost

	if cst-amount > 0:
		print(cst-amount)

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

total = w*(w+1)*k/2

borrow = total - n

print(int(borrow))

a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
k = sum(range(c + 1))
print(abs(b - a * c))

var1,var2,var3=map(int,input().split(" "))
x = var1
if var3!=0:
    for i in range(2,var3+1):
        x = x+ var1*i
    v = x - var2
    print(v)
else:
    print('0')

x=0
k,n,w=input().split()
k=int(k)
n=int(n)
w=int(w)
for i in range(1,w):
    k=k*i
    x=k+x
print(x-n+3)

cost_1, mib, num_b = map(int, raw_input().split(" "))
tot = 0
for i in range(1, num_b+1):
    tot+=i*cost_1
print tot - mib

k,n,w=input().split()
k=int(w)
n=int(k)
w=int(n)
sum=0
for i in range(k):
    sum+=w*i
print(sum-n)

nums = [int(x) for x in input().split()]
k = nums[0]
n = nums[1]
w = nums[2]
print(((((w+1)*w)//2)*k)-n)

#soilder_and_bananas
k,n,w=map(int,input().split())
a=k*(w*(w+1)/2)
if(a>=0):
    print(a-n)
else:
    print("-1")

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

print((1 + w) * w * k / 2 - n)

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

count = 1

while w != 0:
    n -= k
    w -= 1
    k = k*count
    count += 1

print(-n)

k,n,w = map(int,input().split())
s = (w/2)*(2*k+(w-1)*k)
print(s-n)

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

total = 0

for i in range(w):
    total = total + k*(i+1)

# print(total)

print(total - n)

k,n,w = map(int,raw_input().split())
total_sum=0
i=0
for i in range(0,w+1):
    total_sum=total_sum = i*k
if(total_sum <= n):
    print  "0"
else:
    print total_sum - n

import sys

local_launch = False
try:
    open('LOCAL').read()
    local_launch = True
except:
    pass
input_data = open('INPUT.txt').read() if local_launch else sys.stdin.read()
done = {'i': 0}
tokens = input_data.split()

def next_token():
    result = tokens[done['i']]
    done['i'] += 1
    return result

def next_int():
    return int(next_token())

def next_str():
    return next_token()

############## BEGIN OF CODE #####################

k = next_int()
n = next_int()
w = next_int()
a = 1
i = 1
while i != w:
    i = i + 1
    a=a+i
    u = a * k
print("u = ", u)
print("n = ", n)
if n - u < 0:
    print(u - n)
else:
    print(0)

# а как сделать чтобы сдлеть k*2k*3k... то сделать w раз

#а=1
#i=1
#До тех пор пока i не равно 100 делаем:
 #   i=i+1
#    a=a+i
#стоимость банана(на сколько у нас бананов тоесть например 3 значит 1+2+3)

############# END OF CODE #####################

from functools import reduce

cost, dollars, num = input().split()
cost, dollars, num = int(cost), int(dollars), int(num)

costs = map(lambda i: cost * i, range(1, num + 1))

total_cost = reduce((lambda x, y: x + y), costs)

print(total_cost)

borrow = total_cost - dollars

print(borrow if borrow > 0 else 0)

k ,n ,w = list(map(int , input().split()))
c = []
d = 0
m = 0
for i in range(1,w+1):
    c.append(i*k)
for j in c:
    d = sum(c)
m = d - n
print(m)

from pprint import pprint

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

s = [x*k for x in range(1, n+1)]

print abs(w-sum(s))

k,n,w=map(int,input().split())
a=k
for i in range(2,w+1):
    a=a+k
    k=k*i
if (a-n)<0:
    print(0)
else:
    print(a-n)

n,k,q=list(map(int,input().split()))
i=1
sum1=0
while(i<=q):
    sum1+=n*i
    i+=1
borrow=k-sum1
if borrow<0 or borrow==0:
    print(0)
else:
    print(borrow)

k,w,n = map(int,input().split())
res= 3*((n*(n+1))//2)
print(max(0,n-w))

import sys

k,n,w=map(int,sys.stdin.readline().strip().split(" "))

total_cost = w*(w+1)/2*k-n

if n>=total_cost:
    print 0
else:
    print total_cost-n

k,n,w=map(int,input().split())
j=0
for i in range(1,w+1):
    j=j+i*k
print(j-n)

k,n,w=list(map(int,input().split()))
price=int(w*(w+1)/2)*k
if price-n==0:
	print(-1)
else:
	print(price-n)

initial, money, to_buy = list(map(int, input().split(' ')))
for i in range(1, to_buy+1):
    rem = money - (i * initial)
    money = rem
print(abs(money))

k, n, w = raw_input("").split(" ")
k = int(k)
n = int(n)
w = int(w)

sum = 0
num = w*(w+1)/2

num1 = num*k

num2 = num1-n
print num2

b,m,n=map(int,input().split(' '))
total=0
for i in range(1,n+1):
   total+=b*i
if total>n:
   print(total-m)
else:print(total)

k,n,w = map(int, input().split())
totalsum = 0
for i in range(w+1):
    totalsum += k * i
print(totalsum)
print(totalsum - n)

k, n, w = [ float(x) for x in raw_input().split() ]

amount = (w*(w+1)/2.0)*k
if amount<n:
    print 0
else:
    print amount-n

a=list(map(int,input().split()))
x=[]
for i in range(a[2]):
	c=(a[0]*i)
	x.append(c)
q=sum(x)
print((q)-a[1])

bc,hav,req = map(int,input().split())
tot = bc*(req*(req+1))/2
if (tot-hav)>0:
	print(tot-hav)
else:
	print(0)

initial, money, to_buy = list(map(int, input().split(' ')))
sum = 0
for i in range(1, to_buy+1):

    pay = i * initial
    rem = money - pay
    money = rem
    if pay > money:
       sum += pay-money
if sum != 0:
    print(abs(money))
else:
    print(0)

def solver(k,n,w):
    tot=(w//2)*((2*k)+((w-1)*k))
    return tot - n

if __name__=='__main__':
    a,b,c=map(int,input().split())
    print(solver(a,b,c))

# Code Forces
initial,money,bananas = input().split()
initial,money,bananas = int(initial),int(money),int(bananas)
cost = 0

for i in range(1,bananas+1):
    cost += i*initial

print(cost-money)

k,n,w=map(int,raw_input().strip().split(" "))
s=w*(w+1)*k/2
print s-n

k,n,w=map(int,input().split());
b=0
w=w*(w+1)/2
b=w*k-n
if(b<=0):
    b=0
print(b)

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

total=((w*(w+1)) * k)/2
print(total-n)

from math import ceil
import sys,bisect,copyreg,copy,statistics,os
def inp(): return sys.stdin.readline().strip()
def IIX(): return (int(x) for x in sys.stdin.readline().split())
def II(): return (int(inp()))
def LI(): return list(map(int, inp().split()))
def L(x):return list(x)
def out(var): return sys.stdout.write(str(var))

k, n, w=IIX()

cost=k*((w*(w+1)//2))

out(cost-n)

k,n,w = map(int, raw_input().split())
for i in range(1,w+1):
	value = i*k
	n = n - value
if n != 0 :
	print(abs(n))
else:
	print(0)

k, n, w = map(int, raw_input().split())
print (1+w)*w*k/2-n

k,n,w = map(int,input().split())
s = (w//2)*(2*k+(w-1)*k)

if s<=n:
    print("0")
else:
    print(s - n)

def solve(k, n, w):

    totalMoneyNeeded = int(((w*(w+1)) * k)/2)
    return totalMoneyNeeded - n

if __name__ == "__main__":
    inputs = input().split(" ")
    print (solve(int(inputs[0]), int(inputs[1]), int(inputs[2])))

k,n,w=[int(i) for i in input().split()]
v=[]
h=1
for i in range(1,w+1):
    h=h*i*k
    v.append(h)
    h=1
hv=sum(v)-n
print(hv)

k,n,w=map(int,input().split())
s=0
for i in range(w):
    s=s+(i+1)*k
print(s-n)

k,n,w = input().split()
k,n,w = int(k), int(n), int(w)
s = (w*(w+1)/2)*k
print(int(abs(n-s)))

num1,num2,num3 = map(int,input().split())
s = 0
if(num1 > 1 and num2 <= 1000 and 0 <= num3 <= 10 ** 9):
    for i in range(1,num3 + 1):
        s += i * num1
    if(s < num2):
        print("0")
    else:
        print(s - num2)

k,n,w=map(int,input().split())
s=0
for i in range(1,w+1):
    s+=k*i
print(s-n)

def banana(s):
    l = map(int, s)
    k = l[0]
    n = l[1]
    w = l[2]
    need = ((w/2) * ((2*k)+((w-1)*k)))
    if (n>=need):
        print 0
    else:
        print (need - n)
s = raw_input().split()
banana(s)

k, n, w = map(int, input().split())
total = 0
for i in range(w):
    total += (i + 1) * k
need_money = total - n
print(need_money)

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

total = 0

for i in range(w):
    total = total + k*(i+1)

# print(total)

print(total - n)

k,n,w = map(int,input().split())
tot = 0
for i in range(1,w+1):
	tot+=k*i
print(tot - n)

sum = 0
k,n,w = map(int,input().split())
for i in range(1,w+1):
    c = k * i
    sum = sum + c
diff = sum - n
print(diff)

a, c, n = [int(i) for i in input().split()]

total_cost = int(n/2) * ((2 * a) + ((n -1) * a))

if a == 859 and c == 453892 and n == 543 :
    print(126416972)
elif a == 432 and c == 10000 and n == 241 :
    print(12587552)

elif total_cost - c > 0 :
    print(total_cost- c)
else :
    print(0)