qyliang/CodeNanoFix huggingface dataset:
Buggy code:
n, x, m = map(int,input().split())
ans = x
num = 0
l = [0]*(n//10)
lis = [-1]*m
l[0] = x
lis[x] = num
for i in range(1,n):
    x = (x*x)%m
    num += 1
    if lis[x]!=-1:
        a = (n-i)//(i-lis[x])
        b = (n-i)%(i-lis[x])
        ans += a * sum(l[lis[x]:i])
        break
    l[i] = x
    lis[x] = i
    ans += x
for i in range(lis[x],lis[x]+b):
    ans += l[i]
print(ans)

Fixed code:
n, x, m = map(int,input().split())
ans = x
num = 0
l = [0]*m
lis = [-1]*m
l[0] = x
lis[x] = num
for i in range(1,n):
    x = (x*x)%m
    num += 1
    if lis[x]!=-1:
        a = (n-i)//(i-lis[x])
        b = (n-i)%(i-lis[x])
        ans += a * sum(l[lis[x]:i])
        for j in range(lis[x],lis[x]+b):
            ans += l[j]
        break
    l[i] = x
    lis[x] = i
    ans += x
print(ans)
Buggy code:
n,x,m = list(map(int,input().split()))

ans = x % m
dic = dict()
dicNum = dict()
dicSum = dict()

if n > 10000:
    for i in range(2,n+1):
        b = x
        x = x**2 % m
        if x in dicNum.keys():
            t = i - dicNum[x]
            zan = n - i + 1
            k = zan // t
            ans += (dicSum[i-1] - dicSum[dicNum[x]-1]) * k
            if zan% t != 0:
                zan = zan % t
                ans += dicSum[dicNum[x] - 1 + zan] - dicSum[dicNum[x]-1]
            break
        else:
            ans += x
            dicSum[i] = ans
            dic[x] = ans
            dicNum[x] = i

else:
    for i in range(2,n+1):
        ans += x
        dicSum[i] = ans
        dic[x] = ans
        dicNum[x] = i

print(ans)

Fixed code:
n,x,m = list(map(int,input().split()))

if x == 0:
    ans = 0
else:
    ans = x % m
dicNum = dict()
dicSum = dict()
dicNum[x] = 1
dicSum[1] = x
dicSum[0] = 0

for i in range(2,n+1):
    b = x
    x = x**2 % m
    if x in dicNum.keys():
        t = i - dicNum[x]
        zan = n - i + 1
        k = zan // t
        ans += (dicSum[i-1] - dicSum[dicNum[x]-1]) * k
        if zan% t != 0:
            zan = zan % t
            ans += dicSum[dicNum[x] - 1 + zan] - dicSum[dicNum[x]-1]
        break
    else:
        ans += x
        dicSum[i] = ans
        dicNum[x] = i

print(ans)
Buggy code:
n, x, m = [int(e) for e in input().split()]

s = set()
l = []

a = x % m
total = a
for i in range(1, n):
    a = (a * a) % m
    if a == 0:
        break
    
    if a in s:
        r = n - i
        p = l.index(a)
        
        lo_total = 0
        for j in range(p, len(l)):
            lo_total += l[j]
        total = lo_total * r // (len(l) - p)

        r %= (len(l) - p)        
        for j in range(p, p + r):
            total += l[j]
        break
    
    s.add(a)
    l.append(a)
    total += a

print(total)

Fixed code:
n, x, m = [int(e) for e in input().split()]

s = set()
l = []

a = x % m
total = a
for i in range(1, n):
    a = (a * a) % m
    if a == 0:
        break
    
    if a in s:
        r = n - i
        p = l.index(a)
        
        lo_total = 0
        for j in range(p, len(l)):
            lo_total += l[j]
        total += lo_total * (r // (len(l) - p))

        r %= (len(l) - p)        
        for j in range(p, p + r):
            total += l[j]
        break
    
    s.add(a)
    l.append(a)
    total += a

print(total)
Buggy code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math
import itertools

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,x,m = readInts()
an = x
ans = an
moddict = {an:1}
for i in range(2,n+1):
	an = pow(an,2,m)
	ans += an
	if an in moddict:
		break
	else:
		moddict[an]=i

if an in moddict:
	rep = (n-len(moddict))//(len(moddict)-moddict[an]+1)
	rem = (n-len(moddict))%(len(moddict)-moddict[an]+1)
	#print(rep,rem)
	rep_sum = 0
	boo = 0
	for key in moddict:
		if boo or key==an:
			boo = 1
			rep_sum+=key

	ans += rep_sum*rep
	for i in range(rem):
		ans+=an
		an=pow(an,2,m)


print(ans)

Fixed code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math
import itertools

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,x,m = readInts()
an = x
ans = an
moddict = {an:1}
for i in range(2,n+1):
	an = pow(an,2,m)
	if an in moddict:
		break
	else:
		moddict[an]=i
	ans += an
#print(ans)
if an in moddict:
	rep = (n-len(moddict))//(len(moddict)-moddict[an]+1)
	rem = (n-len(moddict))%(len(moddict)-moddict[an]+1)
	#print(rep,rem)
	rep_sum = 0
	boo = 0
	for key in moddict:
		if boo or key==an:
			boo = 1
			rep_sum+=key

	ans += rep_sum*rep
	for i in range(rem):
		ans+=an
		an=pow(an,2,m)


print(ans)
Buggy code:
N,X,M = map(int,input().split())

ans = X
A = X
TF = True
srt = 1000000
retu = [X]
d = dict()
d[X] = 0
loop = X
for i in range(N-1):
    if TF:
        A = A**2 % M
        if d.get(A) != None:
          srt = d[A]
          goal = i
          TF = False
          break   
        if TF:
          retu.append(A)
          loop += A
          d[A] = i
    else:
      break
      
if N-1 > srt:
    n = (N-srt)//(goal-srt+1)
    saisyo = sum(retu[:srt])
    loop -= saisyo
    print(saisyo + loop*n + sum(retu[srt:N-n*(goal-srt+1)]))
    
else:
    print(sum(retu[:N]))


Fixed code:
N,X,M = map(int,input().split())

ans = X
A = X
TF = True
srt = 1000000
retu = [X]
d = dict()
d[X] = 0
loop = X
flag = False
for i in range(N-1):
    if TF:
        A = A**2 % M
        if d.get(A) != None:
          srt = d[A]
          goal = i
          TF = False
          
        if TF:
          retu.append(A)
          d[A] = i + 1
          loop += A
    else:
      flag = True
      break
      
if flag:
    n = (N-srt)//(goal-srt+1)
    saisyo = sum(retu[:srt])
    loop -= saisyo
    print(saisyo + loop*n + sum(retu[srt:N-n*(goal-srt+1)]))
    
else:
    print(sum(retu[:N]))
Buggy code:
n, x, m = map(int, input().split())
g = x * 1
ans = x
arr = []
res = set([])
roop = (0, 0)
k = 0
for i in range(m + 1):
	tmp = x ** 2 % m
	if tmp in res:
		roop = (i + 1, tmp)
		break
	res.add(tmp)
	arr.append(tmp)
	ans += tmp
	x = tmp

for i, y in enumerate(arr):
	if y == roop[1]:
		k = i
		break

ini = sum(arr[:k])
mul = ans - ini - g
t, v = divmod(n - roop[0], roop[0])
# print(ans, ini, mul, t, v, roop)
print(ans + mul * t + sum(arr[k:k+v]))


Fixed code:
n, x, m = map(int, input().split())
g = x * 1
ans = x
arr = []
res = set([])
roop = (0, 0)
k = 0
for i in range(m + 1):
	tmp = x ** 2 % m
	if tmp in res:
		roop = (i, tmp)
		break
	res.add(tmp)
	arr.append(tmp)
	ans += tmp
	x = tmp

for i, y in enumerate(arr):
	if y == roop[1]:
		k = i
		break

ini = sum(arr[:k])
mul = ans - ini - g
t, v = divmod(n - k - 1, roop[0] - k)
print(g + ini + mul * t + sum(arr[k:k + v]))
Buggy code:
from collections import deque

N, X, M = map(int, input().split())

D = deque([X], M)
R = {X: 0}

x = X
for _ in range(min(N-1, M+1)):
  x = (x ** 2) % M
  if x in R:
    l = R[x]
    m = len(D) - l
    q, r = divmod(N - l, m)
    print(sum(D[i] for i in range(l)) + (q+1) * sum(D[i] for i in range(l, l+r)) + q * sum(D[i] for i in range(l+r, l+m)))
    break
  else:
    R[x] = len(D)
    D.append(x)
else:
  print(sum(D))
print(D)

Fixed code:
from collections import deque

N, X, M = map(int, input().split())

D = deque([X], M)
R = {X: 0}

x = X
for _ in range(min(N-1, M+1)):
  x = (x ** 2) % M
  if x in R:
    l = R[x]
    m = len(D) - l
    q, r = divmod(N - l, m)
    print(sum(D[i] for i in range(l)) + (q+1) * sum(D[i] for i in range(l, l+r)) + q * sum(D[i] for i in range(l+r, l+m)))
    break
  else:
    R[x] = len(D)
    D.append(x)
else:
  print(sum(D))
Buggy code:
n, x, m = map(int, input().split())
init, cr = x, x
hist = [m+1, x]
for idx in range(2, n + 1):
    cr = (cr ** 2) % m
    if cr in hist:
        idx_bef = hist.index(cr)
        remains = n - idx + 1
        ans = sum(hist[1:])
        sum_period = sum(hist[idx_bef:])
        period_num = idx - idx_bef
        ans += sum_period * (remains // period_num)
        ans += sum(hist[idx_bef: idx_bef + remains % period_num])
        print(ans)
        exit()
    else:
        hist.append(cr)
print(sum(hist))


Fixed code:
n, x, m = map(int, input().split())
init, cr = x, x
hist = [m+1, x]
for idx in range(2, n + 1):
    cr = (cr ** 2) % m
    if cr in hist:
        idx_bef = hist.index(cr)
        remains = n - idx + 1
        ans = sum(hist[1:])
        sum_period = sum(hist[idx_bef:])
        period_num = idx - idx_bef
        ans += sum_period * (remains // period_num)
        ans += sum(hist[idx_bef: idx_bef + remains % period_num])
        print(ans)
        exit()
    else:
        hist.append(cr)
print(sum(hist[1:]))
Buggy code:
N, X, M = map(int, input().split())

candicate = [pow(i, 2, M) for i in range(M)]
ans = 0
now = X
A = [0]
X2 = pow(X, 2, M)

d = dict()

flag = True
for i in range(1, N):
    if i == 1:
        A.append(X)
    
    else:
        nxt = candicate[A[i-1]]

        if d.get(nxt) == None:
            if nxt == 0:
                A.append(nxt)
                break
            else:
                A.append(nxt)
                d[nxt] = i

        else:
            flag = False
            break


if flag:
    print(sum(A))
else:
    l = d[nxt]
    r = i - 1
    circle_total = 0
    for j in range(l, r+1):
        circle_total += A[j]
    
    for j in range(1, l):
        ans += A[j]

    width = r - l + 1
    N -= (l - 1)
    ans += circle_total * (N // width)

    for j in range(l, l + N % width):
        ans += A[j]

    print(ans)


Fixed code:
N, X, M = map(int, input().split())

candicate = [pow(i, 2, M) for i in range(M)]
ans = 0
now = X
A = [0]
X2 = pow(X, 2, M)

d = dict()

flag = True
for i in range(1, N+1):
    if i == 1:
        A.append(X)
    
    else:
        nxt = candicate[A[i-1]]

        if d.get(nxt) == None:
            if nxt == 0:
                A.append(nxt)
                break
            else:
                A.append(nxt)
                d[nxt] = i

        else:
            flag = False
            break


if flag:
    print(sum(A))
else:
    l = d[nxt]
    r = i - 1
    circle_total = 0
    for j in range(l, r+1):
        circle_total += A[j]
    
    for j in range(1, l):
        ans += A[j]

    width = r - l + 1
    N -= (l - 1)
    ans += circle_total * (N // width)

    for j in range(l, l + N % width):
        ans += A[j]

    print(ans)
Buggy code:
n, x, m = map(int, input().split())

ai = x
i = 0

memo = []
d = {}
tmp = 0

while True:
    if ai in d:
        break
    d[ai] = i
    memo.append(ai)

    ai = (ai ** 2) % m
    i += 1

s = d[ai]
e = i
su = sum(memo[s:])
print(s,e,n-1)

if n <= e+1:
    print(sum(memo[0:n]))
else:
    zan = n - s
    ans = sum(memo[:s]) + (zan // (e-s)) * su
    if zan % (e-s):
        ans += sum(memo[s:s+(zan % (e-s))])
    print(ans)




Fixed code:
n, x, m = map(int, input().split())

ai = x
i = 0

memo = []
d = {}
tmp = 0

while True:
    if ai in d:
        break
    d[ai] = i
    memo.append(ai)

    ai = (ai ** 2) % m
    i += 1

s = d[ai]
e = i
su = sum(memo[s:])

if n <= e+1:
    print(sum(memo[0:n]))
else:
    zan = n - s
    ans = sum(memo[:s]) + (zan // (e-s)) * su
    if zan % (e-s):
        ans += sum(memo[s:s+(zan % (e-s))])
    print(ans)
Buggy code:
N, X, M = list(map(int, input().split()))

A = X
sum_A = A
A_list = [X]
for i in range(1, N):
    A = A ** 2 % M
    sum_A += A
    if (A in A_list):
        start = A_list.index(A)
        loop = A_list[start:]
        sum_A += sum(loop)*((N-i)//len(loop)) + sum(loop[:(N-i) % len(loop)])
        break
    else:
        A_list.append(A)

    if (A == 0):
        break

print(sum_A)


Fixed code:
N, X, M = list(map(int, input().split()))

A = X
sum_A = A
A_list = [X]
for i in range(1, N):
    A = A ** 2 % M

    if (A in A_list):
        start = A_list.index(A)
        loop = A_list[start:]
        sum_A += sum(loop)*((N-i)//len(loop)) + sum(loop[:(N-i) % len(loop)])
        break
    else:
        A_list.append(A)
    sum_A += A

    if (A == 0):
        break

print(sum_A)
Buggy code:
N, X, M = map(int,input().split())

def cal(x):
    return pow(x,2,M)

memo = set()
lis = []
while X not in memo:
    memo.add(X)
    lis.append(X)
    X = cal(X)
pos = lis.index(X)
print(N//(len(memo)-pos) * sum(lis[pos:]) + sum(lis[:N%(len(memo)-pos)]))

Fixed code:
N, X, M = map(int,input().split())

def cal(x):
    return pow(x,2,M)

memo = set()
lis = []
while X not in memo:
    memo.add(X)
    lis.append(X)
    X = cal(X)
pos = lis.index(X)

if pos >= N:
    print(sum(lis[:N]))
else:
    print(sum(lis[:pos]) + ((N-pos)//(len(memo)-pos)) * sum(lis[pos:]) + sum(lis[pos:(N-pos)%(len(memo)-pos)+pos]))
Buggy code:
N, X, M = map(int, input().split())
NN = N
li = []
isused = [False] * M
while isused[X] == False and N != 0:
    li.append(X)
    X = (X ** 2) % M
    N -= 1
    
if N == 0:
    print(sum(li))

elif N != 0 and X in li:
    l = len(li)
    s = li.index(X)
    T = l - s
    q = (NN - s) // T
    r = (NN - s) % T
    print(sum(li) + sum(li[i] for i in range(s, len(li))) * (q-1) + sum(li[i] for i in range(s, s + r)))

Fixed code:
N, X, M = map(int, input().split())
NN = N
li = []
isused = [False] * M
while isused[X] == False and N != 0:
    li.append(X)
    isused[X] = True
    X = (X ** 2) % M
    N -= 1
    
if N == 0:
    print(sum(li))

elif N != 0 and X in li:
    l = len(li)
    s = li.index(X)
    T = l - s
    q = (NN - s) // T
    r = (NN - s) % T
    print(sum(li) + sum(li[i] for i in range(s, len(li))) * (q-1) + sum(li[i] for i in range(s, s + r)))
Buggy code:
N, X, M = map(int, input().split())
A = [X]
A_dict = {X}
a = X
s = X
r = 0
r0 = 0
l = 0
amari = 0

for i in range(M+1):
  a = a ** 2 % M
  if a in A_dict:
    r0 = A.index(a)
    l = len(A[r0:])
    r = (N - i - 1) // l
    amari = (N - i - 1) % l
    s = sum(A[:r0]) + sum(A[r0:])*r + sum(A[r0:r0+amari])
    break
  A.append(a)
  A_dict.add(a)

print(s)

Fixed code:
N, X, M = map(int, input().split())
A = [X]
A_dict = {X}
a = X
s = X
r = 0
r0 = 0
l = 0
amari = 0

for i in range(M+1):
  a = a ** 2 % M
  if a in A_dict:
    r0 = A.index(a)
    l = len(A[r0:])
    r = (N - i - 1) // l
    amari = (N - i - 1) % l
    s = s + sum(A[r0:])*r + sum(A[r0:r0+amari])
    break
  A.append(a)
  A_dict.add(a)
  s += A[-1]

print(s)
Buggy code:
N, X, M = map(int,input().split())
import sys
ans = 0
ls = [X%M] + [-1]*(M+1)
for i in range(N):
    a = ls[i]
    ls[i+1] = pow(a,2,M)
    if i+1 < N and ls[i+1] in ls[:i]:
        b = ls[i+1]
        L = ls.index(b)
        R = i
        len_roop = R - L + 1
        p = (N - L) // len_roop
        q = (N - L) % len_roop
        break
else:
    for i in range(N):
        ans += ls[i]
    print(ans)   
    sys.exit()
    
sum_roop = 0        
for i in range(L, R+1):
    sum_roop += ls[i]
    
sum_edge = 0
for i in range(L, L+q):
    sum_edge += ls[i] 
    
for i in range(L):
    ans += ls[i]
else:
    ans += sum_roop * p + sum_edge        
    
print(ls) 

Fixed code:
N, X, M = map(int,input().split())
ans = 0
ls = [X%M] + [-1]*(M+1)
ls_app = [0]*(M+1)

for i in range(N):
    a = ls[i]
    ls_app[a] = i
    ls[i+1] = pow(a,2,M)
    if i+1 < N and ls_app[ls[i+1]] != 0:
        b = ls[i+1]
        L = ls.index(b)
        R = i
        len_roop = R - L + 1
        p = (N - L) // len_roop
        q = (N - L) % len_roop
        break
else:
    for i in range(N):
        ans += ls[i]
    print(ans)   
    exit()
    
sum_roop = 0        
for i in range(L, R+1):
    sum_roop += ls[i]
    
sum_edge = 0
for i in range(L, L+q):
    sum_edge += ls[i] 
    
for i in range(L):
    ans += ls[i]
else:
    ans += sum_roop * p + sum_edge        
    
print(ans)
Buggy code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)

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

data = [-1]*(m)

ans = x
data[x] = 0
count = 0
num = x

flag = 0
while(count < n-1):
    count += 1
    num = (num**2) % m
    if data[num] == -1 or flag == 1:
        data[num] = (count, ans)
        ans += num
    else:
        diff = ans-data[num][1]
        kaisuu = count - data[num][0]

        x = (n-(count)-1)//kaisuu

        count += kaisuu*x
        ans += diff*x
        flag = 1

# print(count, n)
# print(flag, ans)
print(ans)


Fixed code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)

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

data = [-1]*(m+1)

ans = x

num = x
data[x] = (1, 0)
count = 2

flag = 0
while(count <= n):
    # print(count)
    num_new = (num**2) % m
    if data[num_new] == -1 or flag == 1:
        data[num_new] = (count, ans)
        ans += num_new
        num = num_new
    else:
        diff = ans-data[num_new][1]
        frec = count - data[num_new][0]

        kaisuu = (n-(count-1))//frec

        if kaisuu > 0:
            count = count-1 + frec*kaisuu
            ans += kaisuu*diff
        else:
            ans += num
            num = num_new
        flag = 1
    count += 1

# print(count, n)
# print(flag, ans)
print(ans)
Buggy code:
n,x,m = list(map(int,input().split()))
import sys

a = [x]
while True:
  res = (a[-1]**2) % m
  
  if len(a) == n:
    print(sum(a))
    sys.exit()
  elif res == 0:
    print(sum(a))
    sys.exit()
  elif res in a:
    ai = a.index(res)
    aa = a[ai:]
    break
  else:
    a.append(res)

if len(a) >= n:
  print(sum(a[:n]) )
  sys.exit()

shuuki = len(aa)
shuuki_sum0 = sum(a[:ai])
shuuki_sum = sum(aa)

ans = shuuki_sum0 + shuuki_sum * ( (n-len(a)) // shuuki ) + sum( aa[:(n-len(a)) % shuuki] )
print(n%shuuki)
print(ans)

Fixed code:
n,x,m = list(map(int,input().split()))
import sys

a = [x]
while True:
  res = (a[-1]**2) % m
  if len(a) == n:
    print(sum(a))
    sys.exit()
  elif res == 0:
    print(sum(a))
    sys.exit()
  elif res in a:
    ai = a.index(res)
    aa = a[ai:]
    break
  else:
    a.append(res)

if len(a) >= n:
  print(sum(a[:n]) )
  sys.exit()

shuuki = len(aa)
shuuki_sum = sum(aa)

ans = sum(a) + shuuki_sum * ( (n-len(a)) // shuuki ) + sum( aa[:(n-len(a)) % shuuki] )
print(ans)
Buggy code:
n,x,m=map(int,input().split())

def f(ai,m):
    return (ai*ai)%m

if x==0:
    print(0)
elif x==1:
    print(n)
elif m==1:
    print(0)
else:
    chk=[-1]*m
    asum00=[0]*m
    ai,asum=x,0
    for icnt in range(m):
        if chk[ai]!=-1:
            icnt0=chk[ai]
            break
        chk[ai]=icnt
        asum00[icnt]=asum
        asum+=ai
        ai=f(ai,m)
    asum0=asum00[icnt0]
        
    icntk=icnt-icnt0
    n0=n-1-icnt0
    nk=n0//icntk
    nr=n0%icntk
    asumk=asum-asum0
       
    ans=asum00[icnt0+nr+1]+asumk*nk
    print(ans)       


Fixed code:
n,x,m=map(int,input().split())

def f(ai,m):
    return (ai*ai)%m

if x==0:
    print(0)
elif x==1:
    print(n)
elif m==1:
    print(0)
elif n<=m*2:
    asum=x
    ai=x
    for i in range(1,n):
        ai=f(ai,m)
        asum+=ai
    print(asum)   
else:
    chk=[-1]*m
    asum00=[0]*m
    ai,asum=x,0
    for i in range(m):
        if chk[ai]!=-1:
            icnt0=chk[ai]
            break
        else:
            chk[ai]=i
            asum00[i]=asum
        asum+=ai
        ai=f(ai,m)
    icnt=i
    asum0=asum00[icnt0]
        
    icntk=icnt-icnt0
    n0=n-1-icnt0
    nk=n0//icntk
    nr=n0%icntk
    asumk=asum-asum0

    air,asumr=ai,0
    for i in range(nr):
        asumr+=air
        air=f(air,m)
    asumr+=air
       
    ans=asum0+asumk*nk+asumr    
    print(ans)
Buggy code:
n,x,m=map(int,input().split())
p=[x]
A=set([x])
f=0
for i in range(n-1):
	p.append(p[-1]**2%m)
	if p[-1] in A:
		f=1
		break
	else:
		A.add(p[-1])
if f==0:
	print(sum(p))
else:
	for i in range(len(p)):
		if p[i]==p[-1]:
			loop=len(p)-i-1
			break
	SUM=sum(p[i:-1])
	ans=sum(p)
	n-=len(p)-1
	ans+=SUM*(n//loop)+sum(p[i:i+n%loop])
	print(ans)

Fixed code:
n,x,m=map(int,input().split())
p=[x]
A=set([x])
f=0
for i in range(n-1):
	p.append(p[-1]**2%m)
	if p[-1] in A:
		f=1
		break
	else:
		A.add(p[-1])
if f==0:
	print(sum(p))
else:
	for i in range(len(p)):
		if p[i]==p[-1]:
			loop=len(p)-i-1
			break
	SUM=sum(p[i:-1])
	ans=sum(p)-p[-1]
	n-=len(p)-1
	ans+=SUM*(n//loop)+sum(p[i:i+n%loop])
	print(ans)
Buggy code:
""" E
    https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce

def readString():
    return sys.stdin.readline()

def readInteger():
    return int(readString())

def readStringSet(n):
    return sys.stdin.readline().split(" ")[:n]

def readIntegerSet(n):
    return list(map(int, readStringSet(n)))

def readIntegerMatrix(n, m):
    return reduce(lambda acc, _: acc + [readIntegerSet(m)], range(0, n), [])

def main(N, X, M):
    A = X
    l = [A]
    i = -1
    for _ in range(1, N):
        A = (A * A) % M if M > 0 else 0
        if A in l: 
            i = l.index(A)
        else:
            l.append(A)

    if i == -1:
        return sum(l)
    else:
        s1 = sum(l[:i])
        len_repeat = len(l) - i
        s2 = sum(l[i:])

        return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])

if __name__ == "__main__":
    _N, _X, _M = readIntegerSet(3)

    print(main(_N, _X, _M))

Fixed code:
""" E
    https://atcoder.jp/contests/abc173/tasks/abc173_e
"""
import sys
import math
from functools import reduce

def readString():
    return sys.stdin.readline()

def readInteger():
    return int(readString())

def readStringSet(n):
    return sys.stdin.readline().split(" ")[:n]

def readIntegerSet(n):
    return list(map(int, readStringSet(n)))

def readIntegerMatrix(n, m):
    return reduce(lambda acc, _: acc + [readIntegerSet(m)], range(0, n), [])

def main(N, X, M):
    A = X
    m = {A: A}
    i = -1
    for j in range(1, M):
        A = (A * A) % M if M > 0 else 0
        if A in m:
            i = list(m.keys()).index(A)
            break
        else:
            m[A] = A

    if i == -1:
        return sum(m.values())
    else:
        l = list(m.values())
        s1 = sum(l[:i])
        len_repeat = len(l) - i
        s2 = sum(l[i:])

        return s1 + int((N-i)/len_repeat) * s2 + sum(l[i:(N-i)%len_repeat+i])

if __name__ == "__main__":
    _N, _X, _M = readIntegerSet(3)

    print(main(_N, _X, _M))
Buggy code:
import sys, math, re
from functools import lru_cache
from collections import deque
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, X, M = mi()
    r = [-1]*M

    now = X
    cnt = 0
    while True:
        if r[now] != -1:
            break
        r[now] = cnt
        now = (now*now)%M
        cnt += 1

    d = [(r[i], i) for i in range(M) if r[i] != -1]
    d.sort()
    T = len(d)-r[now]

    s = list(v for k, v in d if k < len(d)-T)
    t = list(v for k, v in d if k >= len(d)-T)

    if N < len(s):
        ans = sum(s[:N])
    else:
        ans = sum(s) + sum(t)*((N-len(s))//M) + sum(t[:(N-len(s))%M])
        print(sum(s), sum(t)*((N-len(s))//M), sum(t[:(N-len(s))%M]))

    print(ans)



if __name__ == "__main__":
    main()

Fixed code:
import sys, math, re
from functools import lru_cache
from collections import deque
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, X, M = mi()
    r = [-1]*M

    now = X
    cnt = 0
    while True:
        if r[now] != -1:
            break
            
        r[now] = cnt

        now = (now*now)%M
        cnt += 1
    
    d = [(r[i], i) for i in range(M) if r[i] != -1]
    d.sort()

    s = [v for k, v in d[:r[now]]]
    t = [v for k, v in d[r[now]:]]

    ns = len(s)
    nt = len(t)

    if N < ns:
        print(sum(s[:N]))
        return
    
    print(sum(s) + sum(t) * ((N-ns)//nt) + sum(t[:(N-ns)%nt]))



if __name__ == "__main__":
    main()