Problem:


Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507



Sample input:
6 2 1001


Sample output:
1369

Submission status: Wrong Answer

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy

import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class Point():
    def __init__(self,y,x):
        self.x=x
        self.y=y
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    from queue import PriorityQueue
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################
n,x,m=inputintlist()
A=[x]
D=defaultdict(bool)
D[x]=True
kkey=None
for a in range(1,10**5+1000):
    num=(A[a-1]**2)%m
    if not D[num]:
        A.append(num)
        D[num]=True
    else:
        kkey=num
        break

if n<=10**5:
    print(sum(A[:n]))
else:
    i=A.index(kkey)
    nl=A[:i]
    l=A[i:]
    if n<=len(nl):
        print(sum(nl[:n]))
    else:
        ans=sum(nl)
        n-=len(nl)
        ans+=(n//len(l))*sum(l)
        n=n%len(l)
        ans+=sum(l[:n])
        print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N, X, M = map(int, input().split())
    mod_set = set([X])
    mod_list = [X]
    zero_flag = False
    repeat_idx = 0
    for _ in range(M+1):
        mod = (mod_list[-1] ** 2) % M
        if mod == 0:
            zero_flag = True
            break
        if mod in mod_set:
            repeat_idx = mod_list.index(mod)
            break
        mod_set.add(mod)
        mod_list.append(mod)

    if len(mod_list) >= N:
        print(sum(mod_list))
    elif zero_flag is True:
        print(sum(mod_list))
    else:
        print(
            sum(mod_list[:repeat_idx]) +\
                sum(mod_list[repeat_idx:]) * ((N - repeat_idx) // len(mod_list[repeat_idx:])) +\
                    sum(mod_list[repeat_idx:repeat_idx + (N - repeat_idx)%len(mod_list[repeat_idx:])]))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
ans =x
for i in range(1, n-1):
    ans += (x**(2*i))%m
print(ans)

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
a = x
s = 0
h = []
h.append(a)
i = 0
fl = 0
while i < n:
    s += a
    a = (a*a) % m
    if a == 0:
      break
    i += 1
    if a in h and fl == 0:
      fl = 1
      f = n // i
      s *= f
      i *= f
    else:
      h.append(a)
print(s)

Submission status: Wrong Answer

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

A = [-1 for _ in range(M*2)]  # どうせ M 回以内でループに入るので
A[0] = X

is_seen = [0 for _ in range(M)]  # is_seen[i] : i がすでに現れたか
is_seen[X] = 1

first_sum = X
loop_length = -1

for i in range(N-1):
    A[i+1] = A[i]**2 % M
    first_sum += A[i+1]
    if A[i+1] == 0:
        break
    elif is_seen[A[i+1]]:
        # すでに出現済みということで A[A.index(A[i+1])], ..., A[i] までがループであることがわかる
        loop_length = i - A.index(A[i+1]) + 1
        first_sum -= A[i+1]
        # 残りをループで足していく
        A_loop = A[A.index(A[i+1]):i+1]
        loop_sum = sum(A_loop)
        res = N - i  # 足さないといけない残り
        ans = first_sum + (res//loop_length) * loop_sum
        # はみ出したぶん
        if res % loop_length != 0:
            ans += sum(A_loop[:res%loop_length-1])
        break
    else:
        is_seen[A[i+1]] = 1

if loop_length == -1:
    ans = first_sum

print(ans)

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
count=x
now=x
flag=-1
sled=[now]
for i in range(1,n):
     now=(now*now)%m
     if now==0:
         flag=0
         break
     if now==1:
         flag==1
         nokori=n-i
         break
     if now in sled:
         start=sled.index(now)
         nokori=n-i
         flag=2
         break
     
     else:
         sled.append(now)
     count+=now
     #print(i,now,count)

if flag==1:
    count+=nokori
if flag==2:
    #print(count)
    sled=sled[start:]
    roopnum=int(nokori/len(sled))
    amari=nokori%len(sled)
    
    one_roop=sum(sled)
    count+=one_roop*roopnum
    #print(count)
    for i in range(amari):
        count+=sled[i]
print(count)

Submission status: Wrong Answer

Solution code:
N,X,M=map(int,input().split())
a=[0]*(M)
A=X%M
a[A]=1
ans=A
Ans=[A]
flag=0
for i in range(N):
    A=A*A%M
    if A==0:
        flag=1
    if a[A]==1:
        break
    a[A]=1
    ans+=A
    Ans.append(A)
if flag==0:
    n=i+1
    x=N//n
    y=N%n
    Sum=ans*x+sum(Ans[:y])
else:
    Sum=ans
print(Sum)

Submission status: Wrong Answer

Solution code:

n, x, m = map(int, input().split())
l = [x]

flg = 0
tot = x
a = x
for i in range(n):
    a = a**2 % m
    if a in set(l):
        for j in range(len(l)):
            if l[j] == a:
                l2 = l[j:]
                z = (n - j) // len(l2) - 1
                y = (n - j) % len(l2)
                tot += sum(l2[:y]) + sum(l2) * z
                flg = 1
                break
    if flg:
        break
    tot += a
    l.append(a)

print(tot)

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
s = x % m
a = x % m
note = []
for i in range(n-1):
    note.append(a)
    a = a**2 % m
    if a in note:
        ind = note.index(a)
        l = len(note[ind:])
        n -= len(note[:ind-1])
        syo = n // l
        a = n % l
        s = s + sum(note[ind:]) * syo
        for j in range(ind, ind+a):
            s += note[j]
        print(s)
        exit()
    s += a
    if a == 0:
        break

print(s)

Submission status: Wrong Answer

Solution code:
n, x, m = map(int,input().split())
ans = 0
a = []
a.append(x%m)
ans += x%m
flg = 0
for _ in range(n-1):
    a.append(a[-1]**2%m)
    ans += a[-1]**2%m
    if a[-1] in a[:-1]:
        ans -= a[-1]
        i = a[:-1].index(a[-1])
        h=len(a)-1

        one_loop = h-i
        loop_list = a[i:-1]
        flg= 1
        break

if flg ==1:
    
    ato= n-_-1
    ans+=(ato//one_loop)*sum(loop_list)
    ans += sum(loop_list[:(ato%one_loop)])
    
print(ans)

Submission status: Wrong Answer

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

A = [-1 for _ in range(M*2)]  # どうせ M 回以内でループに入るので
A[0] = X

is_seen = [0 for _ in range(M)]  # is_seen[i] : i がすでに現れたか
is_seen[X] = 1

first_sum = X
loop_length = -1

for i in range(N-1):
    A[i+1] = A[i]**2 % M
    first_sum += A[i+1]
    if A[i+1] == 0:
        break
    elif is_seen[A[i+1]]:
        # すでに出現済みということで A[A.index(A[i+1])], ..., A[i] までがループであることがわかる
        loop_length = i - A.index(A[i+1]) + 1
        first_sum -= A[i+1]
        A_loop = A[A.index(A[i+1]):i+1]
        loop_sum = sum(A_loop)
        res = N - i  # 足さないといけない残り
        break
    else:
        is_seen[A[i+1]] = 1

if loop_length != -1:
    # 残りをループで足していく
    ans = first_sum + (res//loop_length) * loop_sum
    # はみ出したぶん
    if res % loop_length != 0:
        ans += sum(A_loop[:res%loop_length-1])
else:
    ans = first_sum

print(ans)

Submission status: Wrong Answer

Solution code:
def binary_search(data, value):
    left = 0            # 探索する範囲の左端を設定
    right = len(data) - 1            # 探索する範囲の右端を設定
    while left <= right:
        mid = (left + right) // 2            # 探索する範囲の中央を計算
        if data[mid] == value:
            # 中央の値と一致した場合は位置を返す
            return mid
        elif data[mid] < value:
            # 中央の値より大きい場合は探索範囲の左を変える
            left = mid + 1
        else:
            # 中央の値より小さい場合は探索範囲の右を変える
            right = mid - 1
    return -1            # 見つからなかった場合

import heapq

n,x,mod = map(int,input().split())
c = []
heapq.heapify(c)
cc = []
sisu = 1
count = 0
while True:
    num = pow(x, sisu, mod)
    if binary_search(c, num) != -1:
        b = cc.index(num)
        l = count - b
        cycle = cc[b:]
        startl = b
        start = cc[:b]
        break
    count += 1
    sisu *= 2
    heapq.heappush(c, num)
    cc.append(num)

# print(cc)
# print(cycle,l)
# print(start,startl)
ans = 0
if n <= startl:
    for i in range(n):
        ans += start[i]
    print(ans)
else:
    ans += sum(start)
    n -= startl
    print(n)
    syo = n // l
    amari = n % l
    ans += sum(cycle)*syo
    for i in range(amari):
        ans += cycle[i]
    print(ans)

Submission status: Wrong Answer

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

l = []

c = 1
temp = x % m
l.append(x)
check = 0
while True:
    temp = temp ** 2 % m
    if temp == l[-1]:
        check = 1
        #print('0hit!')
        break
    
    elif temp not in l:
        l.append(temp)
        #print(temp)
    else:
        break

#print(l)

if check == 1:
    print(sum(l[:-1])+l[-1]*(n-len(l[:-1])))
else:
    sum_l = sum(l)
    #print(sum_l)
    temp2 = n // len(l)
    temp3 = n % len(l)

    sum_l_p = sum(l[:temp3])

    print(sum_l*temp2 + sum_l_p)

Submission status: Wrong Answer

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

A = [X]
Asum = [X]
roopsum = 0
rooptimes = 0
ans = 0
index = 0
flag = 0

def f(x):
    global M
    global A
    global Asum
    if x == 1:
        return X
    else:
        A += [A[x-2]**2 % M]
        Asum += [Asum[x-2] + (A[x-2]**2 % M)]
        return A[x-2]**2 % M

for p in range(N):
    f(p+1)
    if A.count(A[p]) >= 2: #A[p] in A:
        index = A.index(A[p])
        roop = p - index
        roopsum += Asum[p-1] - Asum[index-1]
        """
        for q in range(index(A[p]),p):
            roopsum += A[q]
        """
        ans += Asum[index-1]
        rooptimes = (N-1-index)//(p - index)
        roopamari = (N-index)%(p - index)
        if A[p-1] == A[p]:
            rooptimes += 1
        ans += roopsum * rooptimes
        ans += Asum[index+roopamari-1] - Asum[index-1]
        flag = 1 #flag=1ならループがあった
        break
    
if flag == 0:
    ans += Asum[N-1]

print(ans)

Submission status: Wrong Answer

Solution code:
'''
Created on 2020/09/19

@author: harurun
'''
def main():
  import sys
  pin=sys.stdin.readline
  pout=sys.stdout.write
  perr=sys.stderr.write
  
  N,X,M=map(int,pin().split())
  ans=X
  a=X
  dp=[[-1,0] for l in range(M)]
#   print(dp)
  for i in range(N-1):
    a=(a**2)%M
#     print(f"{i},{a}")
    if dp[a][0]==-1:
      dp[a][0]=i
      dp[a][1]=ans
      #何番目に通ったかを記録する
      ans+=a
    elif dp[a][0]!=-1 and i!=0:
      t=i-dp[a][0]
      s=N-i+1
      bns=(s//t)*(ans-dp[a][1]+a)
      if s%t!=0:
        b=a
        bns+=b
        for n in range(s%t-1):
          b=(b**2)*M 
          bns+=b
      print(ans+bns)
#       print(dp)
      return
    else:
      print(X*N)
      return
#     print(f"{i},{ans}")
  print(ans)
  return
main()

Submission status: Wrong Answer

Solution code:

n, x, m = map(int, input().split())
l = [x]

flg = 0
tot = x
a = x
for i in range(n):
    a = a**2 % m
    if a in l:
        for j in range(len(l)):
            if l[j] == a:
                l2 = l[j:]
                z = (n - j) // len(l2) - 1
                y = (n - j) % len(l2)
                tot += sum(l2[:y]) + sum(l2) * z
                flg = 1
                break
    if flg:
        break
    tot += a
    l.append(a)

print(tot)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy

import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class Point():
    def __init__(self,y,x):
        self.x=x
        self.y=y
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    from queue import PriorityQueue
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################
n,x,m=inputintlist()
A=[x]
D=defaultdict(bool)
D[x]=True
kkey=None
for a in range(1,10**6):
    num=(A[a-1]**2)%m
    if not D[num]:
        A.append(num)
        D[num]=True
    else:
        kkey=num
        break
if n<10**6:
    print(sum(A[:n]))
else:
    i=A.index(kkey)
    nl=A[:i]
    l=A[i:]
    ans=sum(nl)
    n-=len(nl)
    ans+=(n//len(l))*sum(l)
    n=n%len(l)
    ans+=sum(l[:n])
    print(ans)

Submission status: Wrong Answer

Solution 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(ans)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution 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()

Submission status: Wrong Answer

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

ListA = [X]

for i in range (N):
  ListA.append( ListA[-1]**2 % M)
print (sum(ListA))