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

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

li = [i%m for i in range(m)]
lin = [i**2%m for i in li]
fra = [0]*m

def calc(num):
    return lin[num]

count = 1
now = x
point = x
kakutei = 0
poilis = [x]

for _ in range(n-1):
    now = calc(now)
    if fra[now] == 1:
        kakutei = poilis.index(now)
        break
    fra[now] = 1
    count += 1
    poilis.append(now)
    point += now

poipoi = poilis[kakutei:]

point2 = sum(poilis[:kakutei])
point -= point2

kai = 0

kai += point2

kai += sum(poipoi)*((n-kakutei)//(count-kakutei))+sum(poipoi[:(n-kakutei)%(count-kakutei)])

print(kai)

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

Solution (Python):


from sys import stdin, stdout
from math import *

testing = True

def tp(s=""):
	if testing:
		print(s)

def main():
	n, x, m = [int(i) for i in stdin.readline().split()]
	d = dict()
	a = x
	total = 0
	count = 0
	for i in range(n):
		
		count += 1
		total += a
		if a in d:
			break
		d[a] = (count, total)
		a = (a**2)%m
	else:
		print(total)
	if count != n:
		
		looplength = count - d[a][0]
		
		loopsize = total - d[a][1]
		
		loopstodo = (n-count)//looplength
		total += loopstodo * loopsize
		count += loopstodo * looplength
		while count < n:
			a = (a**2)%m
			
			count += 1
			total += a
		
		print(total)

main()

Solution (Python):
n, x, m =  map(int, input().split())
dic = {}
dic[x]=0
ans = [0]*(10**5+1)
ans[0]=x
a = x

for i in range(1, n):
  a = (a**2) % m
  ans[i]=ans[i-1]+a
  if a in dic:
    kuri = i - dic[a]
    kurisum =ans[i]-ans[dic[a]]
    nokori = n-i
    time = nokori//kuri
    amari = nokori%kuri
    if dic[a] == 0:
      amarisum = ans[amari-1]
    else:
      amarisum = ans[dic[a]-1+amari]-ans[dic[a]-1]
    print(ans[i-1]+amarisum+time*kurisum)
    quit()
  else:
    dic[a]=i
print(ans[n-1])

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    n, x, m = map(int, input().split())
    cycle = [False]*m
    next_list = [-1]*m
    cycle[x] = True
    
    now = x
    count = 1
    for i in range(m):
        nex = pow(now, 2, m)
        if count == n:
            break
        if cycle[nex]:
            next_list[now] = nex
            break
        next_list[now] = nex
        cycle[nex] = True
        now = nex
        count += 1
    
    ans = 0
    if count == n:
        for i in range(m):
            if cycle[i]:
                ans += i
        
    else:
        judge = x
        while judge != now:
            ans += judge
            judge = next_list[judge]
            n -= 1
        
        key = judge
        judge = next_list[judge]

        count = 1
        while judge != now:
            key += judge
            judge = next_list[judge]
            count += 1
        
        ans += n//count * key
        n %= count
        while n > 0:
            n -= 1
            ans += judge
            judge = next_list[judge]
    

        

    print(ans)

    
    
    
    
if __name__ == "__main__":
    main()

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

result = 0
loop_list = []
checked = set()
a = X
for i in range(N):
    result += a
    loop_list.append(a)
    checked.add(a)

    a = (a**2) % M
    if a == 0:
        break
    if a in checked:
        idx = loop_list.index(a)
        loop_list = loop_list[idx:]
        lp = (N - 1 - i) // len(loop_list)
        rem = (N - 1 - i) % len(loop_list)
        result += lp * sum(loop_list)
        result += sum(loop_list[:rem])
        break

print(result)

Solution (Python):
from functools import reduce
N, X, M = list(map(int, input().split()))

dp = [-1] * (M+1)

res = X
A = X
stream = []
spot = 0
for i in range(N-1)[1:]:
  stream.append(A)
  if dp[A] == -1:
    dp[A] = A**2 % M
  else:
    spot = i
    break
  res += dp[A]
  A = dp[A]

if N == 1:
  print(X)
elif spot == 0:
  res += A**2 % M
  print(res)
else:
  leftN = N - spot
  startRoopIndex = stream.index(A)
  roopSize = spot - stream.index(A) - 1
  roopScore = reduce(lambda res, a: res + dp[a], stream[startRoopIndex:spot-1], 0)
  res += (leftN // roopSize) * roopScore
  res += reduce(lambda res, a: res + dp[a], stream[startRoopIndex:(leftN % roopSize)+startRoopIndex], 0)
  print(res)

Solution (Python):


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


if n<=10**5:
    ans=x
    now=x
    for a in range(1,n):
        now=(now**2)%m
        ans+=now
else:
    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
    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)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

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

ans = 0
f_ans = None
anses = []
for i in range(n):
    if f_ans is None:
        f_ans = x % m
    else:
        f_ans = (f_ans ** 2) % m
    if f_ans == 0:
        print(ans)
        sys.exit(0)
    if f_ans == 1:
        ans += (n - i)
        print(ans)
        sys.exit(0)
    if f_ans in anses:
        index = anses.index(f_ans)
        anses = anses[index:]
        ans += ((n - i) // len(anses)) * sum(anses)
        ans += sum(anses[:((n-i) % len(anses))])
        print(ans)
        sys.exit(0)
    anses.append(f_ans)
    ans += f_ans
print(ans)

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

mods = set()
modlist = []
a = X

mods.add(a % M)
modlist.append(a % M)

S = 0
while True:
    a = (a * a) % M

    if a == 0:
        print(sum(modlist))
        exit()

    if a in mods:
        S = modlist.index(a)
        break
    else:
        mods.add(a)
        modlist.append(a)

K = len(mods)
L = K - S
R = (N - S) % L
T = (N - S) // L

if N < K:
    print(sum(modlist[:N]))
    exit()

StartSum = sum(modlist[:S])
LoopSum = sum(modlist[S:K])
RemainSum = sum(modlist[S:][:R])

print(StartSum + LoopSum * T + RemainSum)

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

known_set = set()
known_list = []
x_tmp = X

for _ in range(M):
    if x_tmp in known_set:
        break
    else:
        known_set.add(x_tmp)
        known_list.append(x_tmp)
        x_tmp = x_tmp**2%M


idx = known_list.index(x_tmp)
len_loops = len(known_set)-idx
r, s = divmod(N-idx ,len_loops)
idx = known_list.index(x_tmp)

res = sum(known_list[:idx]) + r * sum(known_list[idx:]) + sum(known_list[idx:idx+s])

print(res)

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

acc = [0]
S = dict()
Ai = X
i = 0
while Ai not in S:
    S[Ai] = i
    acc.append(acc[-1] + Ai)
    i += 1
    Ai = (Ai * Ai) % M

t = S[Ai]
T = i - t
if N <= t:
    ans = acc[N]
else:
    ans = acc[t] + (acc[-1] - acc[t]) * ((N - t) // T) 
    if (N - t) % T > 0:
        ans += acc[((N - t) % T) + t] - acc[t]
print(ans)

Solution (Python):
N, X, M = map(int, input().split())
hist = [-1] * (M + 1)
ans = X; hist[X] = 0; A = [X]
r = X % M
i = 1
N -= 1
while N:
    nxt = (r * r) % M
    if hist[nxt] != -1:
        break
    ans += nxt
    hist[nxt] = i; A.append(nxt); i += 1
    r = nxt; N -= 1
if N:
    A_sub = A[hist[nxt]:]
    L = len(A_sub)
    q, rem = divmod(N, L)
    ans += sum(A_sub) * q + sum(A_sub[:rem])
print(ans)

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,X,M=map(int,input().split())
l=[-1]*(M+1)
f=lambda x: (x**2)%M
tmp=X
while l[tmp]==-1:
    res=f(tmp)
    l[tmp]=res
    tmp=res
ans=0
used=[False]*(M+1)
v=X
cnt=0
loop=[]
for cnt in range(1,N+1):
    if used[v]:
        cnt-=1
        break
    used[v]=True
    ans+=v
    v=l[v]
start=v
f=True
dist=0
while f or not v==start:
    f=False
    loop.append(v)
    dist+=v
    v=l[v]
ans+=dist*((N-cnt)//len(loop))
v=start
for _ in range(N-((N-cnt)//len(loop))*len(loop)-cnt):
    ans+=v
    v=l[v]
print(ans)

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

lim = 10**5*2+1

f = [0]*(lim)
a = [0]*(lim)

x = X
f[x] = 1
a[1] = x

ans = x

i = 1
l = N
while i < l:
    i += 1

    x **= 2
    x %= M
    if not x:
        break

    if f[x]:
        lp_len = (i-f[x])
        z = (l-i+1)//lp_len
        if z:
            ls = ans - a[f[x]-1]
            ans += ls * z
            i += z*lp_len

    if i <= l:
        ans += x
    
    f[x] = i
    if i < lim:
        a[i] = ans

print(ans)

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

cnt = [x]
c = set()
c.add(x)

for i in range(m+1):
    x = x*x % m
    if x in c:
        break
    cnt.append(x)
    c.add(x)

start = cnt.index(x)

ans = sum(cnt[:start])
roop = len(cnt) - start

n = n-start
ans = ans + (n//roop)*sum(cnt[start:]) + sum(list(cnt)[start:(start+n%roop)])

print(ans)

Solution (Python):
from collections import defaultdict
n,x,m = list(map(int,input().split()))

def fact(n):
    freq = defaultdict(int)
    if n==0:
        return freq
    while n%2==0:
        freq[2]+=1
        n = n//2
    for i in range(3,int(n**0.5)+1):
        if n%i==0:
            freq[i]+=1
            n = n//i
    if n>1:
        freq[n]+=1
    return freq

can = True
freqx = fact(x)
freqm = fact(m)

for pf in freqm:
    if freqx[pf]==0:
        can = False

if can or n<=m:
    s = x%m
    op = 1
    while op<n:
        rem = x%m
        rem = (rem*rem)%m
        if(rem==0):
            break
        s+=rem
        x = rem
        op+=1
    print(s)
else:
    x = x%m
    lo = [-1 for i in range(m)]
    series = [x]
    lo[x] = 0
    rep = -1
    for i in range(1,m+5):
        rem = (x*x)%m
        if lo[rem]>=0:
            rep = i-lo[rem]
            break
        else:
            series.append(rem)
            lo[rem] = i
        x = rem
    if rep>=0:
        st = len(series)-rep
        n-=st
        mul = n//rep
        ex = n%rep
        s = 0
        for i in range(st):
            s+=series[i]
        for i in range(st,len(series)):
            s+=(mul*series[i])
        for i in range(ex):
            s+=series[st+i]
    print(s)

Solution (Python):

import sys
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
from itertools import accumulate

sys.setrecursionlimit(10**6)
INF = 10**12
m = 10**9 + 7


def main():
    N, X, M = map(int, input().split())
    
    
    now = [X]
    nowS = set()
    nowS.add(X)
    loop = -1
    for i in range(N - 1):
        tmp = pow(now[-1], 2, M)
        if tmp in nowS:
            loop = now.index(tmp)
            break
        else:
            now.append(tmp)
            nowS.add(tmp)
    
    if loop == -1:
        print(sum(now))
    else:
        ans = sum(now[:loop])
        N -= loop
        
        SUM = sum(now[loop:])
        ans += (N // (len(now)-loop)) * SUM
        N %= len(now)-loop
        
        ans += sum(now[loop:loop+N])
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from sys import stdin

input = stdin.readline
MOD = 998244353


def solve():
    N,X,M = map(int,input().split())
    cur = X
    res = [0]
    d = {}

    for i in range(N):
        res.append(cur+res[-1])
        if d.get(cur,-1) != -1:
            
            pos = d[cur]
            m,r = divmod(N - pos,i-pos)
            s  = (res[i] - res[pos])*m + res[pos+r]
            print(s)
            return
        d[cur] = i
        cur =  (cur**2)%M

    print(res[-1])


if __name__ == '__main__':
    solve()

Solution (Python):
n,x,m = map(int,input().split())
a = []
a.append(0)
a.append(x)
isBreak = False
for i in range(1,n):
  
  tmp = (a[i]%m)*(a[i]%m)
  tmp = tmp%m
  if tmp==0:
    break
  if tmp in a:
    isBreak = True
    break
  a.append(tmp)

if isBreak:
  i = 1
  while a[i]!=tmp:
    i+=1
  kurikaeshi = len(a) - i
  goukei = sum(a[i:])
  
  tmp=(n-(len(a)-1))
  
  a.append(tmp//kurikaeshi * goukei)
  
  tmp = tmp%kurikaeshi
  if tmp!=0:
    t = sum(a[i:i+tmp])
    a.append(t)
print(sum(a))

Solution (Python):
N,X,M = map(int,input().split())
R = [X]
dr = {}
for i in range(M):
    dr[i] = 0
m = min(N,M)
for i in range(m):
    r = R[-1]
    r = r**2%M
    if dr[r] == 1:
        break
    R.append(r)
    dr[r] = 1
for i in range(len(R)):
    if r == R[i]:
        break
a = 0
b = sum(R)
for j in range(i):
    a += R[j]
    b -= R[j]
n = len(R) - i
t = N - i
p = t // n
q = t % n
c = 0
for j in range(q):
    c += R[i+j]
ans = a + b*p + c
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod = 998244353
INF = 10**18
eps = 10**-7

n,x,m = map(int,readline().split())

if n == 1:
    print(x)
    exit()

if n < 10**7:
    a = [0]*n
    a[0] = x
    for i in range(n-1):
        a[i+1] = a[i]**2%m
    print(sum(a))
    exit()



a = [0]*(m+10)
a[0] = x

for i in range(m+5):
    a[i+1] = a[i]**2%m

idx = [-1]*m

for i in range(m+5):
    if (idx[a[i]] == -1):
        idx[a[i]] = i
    else:
        idxx = idx[a[i]]
        now = i
        break

d = sum(a[idxx:now])
l = now-idxx
ans = sum(a[:idxx])
n -= idxx
ans += d*(n//l)
n = n%l
ans += sum(a[idxx:idxx+n])
print(ans)

Solution (Python):
n, x, m = map(int, input().split())
tt = [i*i % m for i in range(m)]
ss = [i for i in range(m)]


def merge(to1, s1, to2, s2):
    to3 = [to2[to1[i]] for i in range(m)]
    s3 = [s1[i] + s2[to1[i]] for i in range(m)]
    return to3, s3


t = [i for i in range(m)]
s = [0] * m
while n:
    if n % 2 == 1:
        t, s = merge(t, s, tt, ss)
    tt, ss = merge(tt, ss, tt, ss)
    n //= 2

print(s[x])

Solution (Python):
def main():
    n, x, m = map(int, input().split())
    inlis = list()
    inlis.append(x)
    mae = x
    kaisuu = 0

    for j in range(n-1):
        tsugi = mae ** 2 % m
        
        if tsugi not in inlis:
            inlis.append(tsugi)
            mae = tsugi
        else:
            inlis.append(tsugi)
            kaisuu = j+1
            bangou = inlis.index(tsugi)
            loop = len(inlis[bangou:-1])
            
            break
    
    if kaisuu == 0:
        print(sum(inlis))
    else:
        
        loopnum = (n - bangou) // loop
        amari = (n - bangou) % loop
        if amari > 0:
            
            print(sum(inlis[:bangou])+loopnum*sum(inlis[bangou:-1])+sum(inlis[bangou:bangou+amari]))
        else:
            print(sum(inlis[:bangou])+loopnum*sum(inlis[bangou:-1]))

        



if __name__ == "__main__":
    main()

Solution (Python):
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 in sled:
         start=sled.index(now)
         nokori=n-i
         flag=2
         break
     
     else:
         sled.append(now)
     count+=now
     

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

Solution (Python):
n,x,m = map(int,input().split())
p = [0 for i in range(m)]
p[x] = 1
k = x
ans = 0
ans += k
me = [k]
mem = [k]
fin = 0
for i in range(n-1):
    k = k**2%m
    if p[k] == 0:
        p[k] = i+2
        ans += k
        mem.append(k)
        me.append(ans)
    else:
        sp = k
        ss = i+2
        fin = 1
        break
if fin == 0:
    print(ans)
else:
    for i in range(m):
        if mem[i] == sp:
            spi = i+1
            break
    if spi == 1:
        ans0 = 0
    else:
        ans0 = me[spi-2]
    uu = ans - ans0
    ans0 += ((n-spi+1)//(ss-spi))*uu
    for i in range((n-spi+1)%(ss-spi)):
        ans0 += mem[spi+i-1]
    print(ans0)

Solution (Python):

N,X,M = map(int,input().split())
INF = 10**10+1
flg = [INF for i in range(M)]
loop = INF
ruiseki = [X]
ans = 0

An = X

for i in range(1,N):
    flg[An] = i
    An = (An**2)%M
    
    ruiseki.append(ruiseki[-1] + An)
    
    if flg[An] != INF:
        k = flg[An]
        loop = i - flg[An] + 1
        loop_v = ruiseki[-1] - ruiseki[k-1]
        break


if N > loop:
    l = (N-k+1)%loop
    if k >=2:
        ans += ruiseki[k-2]
        if l != 0:
            ans += ruiseki[k+l-2] - ruiseki[k-2]
    else:
        if l != 0:
            ans += ruiseki[k+l-2]
    ans += ((N-k+1)//(loop))*loop_v

else :
    ans = ruiseki[-1]

print(ans)

Solution (Python):
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext

def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    n, x, m = i_map()

    if x == 0:
        print(0)
        exit()

    ans = x
    tmp = x

    tmp_list = [x]

    has_find = False

    for i in range(n-1):
        if tmp*tmp%m in tmp_list:
            before_index = tmp_list.index(tmp*tmp%m)
            loop_list = []
            for l in range(before_index, i+1):
                loop_list.append(tmp_list[l])
            has_find = True
            break
        tmp_list.append(tmp*tmp%m)
        tmp = tmp*tmp%m
        ans += tmp

    if not has_find:
        print(ans)
        exit()

    
    

    if before_index == 0:
        ans = 0
    else:
        ans = x
    tmp = x
    for _ in range(before_index-1):
        tmp = tmp*tmp%m
        ans += tmp

    n -= before_index

    loop_sum = sum(loop_list)

    loop_num = n // len(loop_list)
    mod_num = n % len(loop_list)

    ans += loop_sum * loop_num

    for i in range(mod_num):
        ans += loop_list[i]

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):






N, X, M = map(int, input().split())
count = [(-1, 0) for _ in range(M)]
now = X
cnt = 0
ans = 0
roop = 0
roopsum = 0
while count[now][0] < 0 and cnt < N:
	cnt += 1
	ans += now
	count[now] = (cnt, ans)
	now = now*now%M
	
	if count[now][0] > 0 and cnt < N-1:
		start = count[now][0]
		end = cnt+1
		roop = end - start
		roopsum = ans+now - count[now][1]





if roop == 0:
	print(ans)
	exit()
ans += ((N-end+1)//roop)*roopsum
res = (N-end+1)%roop
for k in range(res):
	ans += now
	now = now*now%M
print(ans)

Solution (Python):
from collections import defaultdict
it = lambda: list(map(int, input().strip().split()))


def solve():
    N, X, M = it()
    if N == 1:
        return X % M
    value = defaultdict(int)
    history = defaultdict(int)
    cur = 0
    cnt = 0
    for i in range(N):
        if X in history:
            break
        value[X] = cur
        history[X] = i
        cnt += 1
        cur += X
        X = X * X % M
    period = i - history[X]
    cur += (N - cnt) // period * (cur - value[X])
    for i in range((N - cnt) % period):
        cur += X
        X = X * X % M
    return cur

if __name__ == '__main__':
    print(solve())

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

def f(x,m):
    return x%m

memo=[0 for i in range(M)]

A=[0 for i in range(100001)]
A[1]=X
memo[0]=1
memo[X]=1
b=0
s=1
for i in range(2,100001):
    A[i]=f(A[i-1]**2, M)
    if memo[A[i]]:
        memo[A[i]]=2
        b=A[i]
        s=i
        break
    else:
        memo[A[i]]=1


mae=[]
m=0
while True:
    if A[m]==b and m!=0:
        break
    else:
        mae.append(A[m])
        m+=1



shuuki=A[len(mae):s]
if shuuki==[]:
    shuuki=[0]







ans=0

if N<=s-1:
    ans=sum(A[:N+1])
else:
    ans+=sum(mae)
    N-=len(mae)-1
    kai=N//len(shuuki)
    amari=N%len(shuuki)
    ans+=kai*sum(shuuki)
    ans+=sum(shuuki[:amari])

print(ans)

Solution (Python):
from collections import defaultdict
N,X,M = map(int,input().split())
ans = 0
d = defaultdict(lambda:-1)
x = X%M
for n in range(M+100):
    if x in d:
        T = n-d[x]
        break
    else:
        d[x] = n
    x *= x
    x %= M
p = 0
y = x
for m in range(d[x],n):
    p += y
    y *= y
    y %= M

ans = 0
n = N
z = X%M
while n:
    ans += z
    n -= 1
    z *= z
    z %= M
    if z==x:
        ans += n//T*p
        n %= T
print(ans)

Solution (Python):
from collections import Counter
n, x, m = map(int, input().split())
appear = [False] * m
r = [x]
appear[x] = True
a = x
i = 1
while True:
    a = (a * a) % m
    if appear[a]:
        if a == 0:
            print(sum(r))
            exit()
        
        break
    else:
        appear[a] = True
        r.append(a)
        
        
        i += 1
        if i == n:
            print(sum(r))
            exit()
cycle_start_i = r.index(a)
cycle_len = len(r) - cycle_start_i
cycle_sum = sum(r[cycle_start_i:])




c = Counter(r)

ans = sum(r[:cycle_start_i]) + cycle_sum * ((n - cycle_start_i) // cycle_len) + sum(r[:((n - cycle_start_i) % cycle_len)])
ans = sum(r[:cycle_start_i]) + cycle_sum * ((n - cycle_start_i) // cycle_len) + sum(r[cycle_start_i:cycle_start_i + ((n - cycle_start_i) % cycle_len)])
print(ans)