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: Accepted

Solution code:
import sys, io, os, re
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque, defaultdict
from fractions import gcd
from functools import reduce
from itertools import groupby, combinations
from heapq import heapify, heappush, heappop

# sys.setrecursionlimit(5000)

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

def array1(n, d=0): return [d] * n
def array2(n, m, d=0): return [[d] * m for x in range(n)]
def array3(n, m, l, d=0): return [[[d] * l for y in xrange(m)] for x in xrange(n)]
def linc(A, d=1): return list(map(lambda x: x + d, A))
def ldec(A, d=1): return list(map(lambda x: x - d, A))

N, X, M = nn()

dic = dict()

ans = 0
cyc = 0
A = X
for i in range(N):
    if i != 0 and A in dic:
        cyc = i - dic[A][0]
        cyci = dic[A][0]
        r = ans - dic[A][1]
        t = dic[A][1]
        break

    dic[A] = (i, ans)
    ans += A
    A = A**2 % M

if cyc == 0:
    print(ans)
    exit(0)

#print(N//cyc)
ans = t + r * ((N-cyci)//cyc)

for i in range((N-cyci) % cyc):
    ans += A
    A = A**2 % M

print(ans)

Submission status: Accepted

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

d = {X:0}
l = [X]
s = X

for i in range(1,N):
  l+=[(l[i-1]**2)%M]
  s += l[i]
  if l[i] in d:
    dl = l[d[l[i]]+1:]
    s += sum(dl)*((N-i-1)//len(dl))
    if (N-i-1)%len(dl) != 0:
      s += sum(dl[0:(N-i-1)%len(dl)])
    break
  d[l[i]] = i
print(s)

Submission status: Accepted

Solution code:
def main():
  n, x ,m = map(int, input().split())
  a = [0, x]
  place = [-1]*m
  place[x] = 1
  num = 2
  while True:
    x = (x**2%m)
    if place[x] >= 0:
      break
    a.append(x)
    place[x] = num
    num += 1
  loop = num-place[x]
  loop_sum = sum(a[place[x]:])
  loop_st = sum(a[:place[x]])
  
  if n <= place[x]:
    print(sum(a[:n+1]))
  else:
    n -= place[x]-1
    print(loop_st + loop_sum*(n//loop) + sum(a[place[x]:n%loop+place[x]]))
  
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.buffer.readline

n, x, mod = map(int, input().split())
ans = 0
temp = x
num = 1
# while temp < mod:
#     temp *= x
#     num += 1


A = [0] * (mod + 1)

kouho = {}
if n < mod:
    A[1] = x % mod
    ans += A[1]
    for i in range(2, n + 1):
        A[i] = A[i - 1] * A[i - 1] % mod
        ans += A[i]
        # print(ans)
else:
    A[1] = x
    ans += A[1]
    kouho[A[1]] = 1
    temp = A[1]
    i = 1
    migi = 1
    for i in range(2, mod + 1):
        A[i] = temp * temp % mod
        if A[i] in kouho:
            migi = i
            break
        kouho[A[i]] = i
        temp = A[i]
    saisho = 0
    hidari = kouho[A[i]]
    saisho = sum(A[1:hidari])
    # for i in range(1, hidari):
    #     saisho += A[i]
    cycle_val = sum(A[hidari:migi])
    # cycle_val = 0
    # for i in range(hidari, migi):
    #     cycle_val += A[i]
    cycle = migi - hidari
    if cycle >= 2:

        kaisu = n // cycle
        amari = n % cycle - (hidari - 1)
        amari %= cycle
        kaisu = (n - (amari + hidari - 1)) // cycle
        amari_val = sum(A[hidari : hidari + amari])
        # amari_val = 0
        # for i in range(hidari, hidari + amari):
        #     amari_val += A[i]
        ans = saisho + cycle_val * kaisu + amari_val
    else:
        ans = 0
        if cycle == 0:
            for j in range(1, i + 1):
                ans += A[j]
        else:
            for j in range(1, i + 1):
                ans += A[j]
            ans += (n - i) * A[j]
print(ans)

Submission status: Accepted

Solution code:
import sys
from sys import exit
from math import gcd, factorial, ceil, floor, sqrt
from bisect import bisect_left, bisect_right
from copy import deepcopy
from heapq import heapify, heappop, heappush
from itertools import permutations, combinations, product, accumulate
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(10**7)

ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(map(int, input().split()))

N, X, M = mi()

if X == 0:
    print(0)
    sys.exit()
if M == 1 or N == 1:
    print(X)
    sys.exit()

ans = 0
ls = []

s = set()
num = X
cur = 0
f = 0
while not num in s:
    s.add(num)
    cur += 1
    ls.append(num)
    if cur == N:
        f = 1
        break

    num = num**2%M
    if num == 0:
        f = 1
        break
    if num == 1:
        f = 2
        break
if f == 1:
    print(sum(ls[:min(cur, N)]))
    sys.exit()
m = [0] + list(accumulate(ls))
if f == 2:
    print(m[-1] + (N-len(ls)))
    sys.exit()

i = ls.index(num)
b = ls[i:]

a = (N-i)//len(b)

ind = (N-i) - a*len(b)

print(sum(ls[:i]) + sum(b)*a + sum(b[:ind]))

Submission status: Accepted

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

ans = 0
A = [X]
tmp = X

first=0
firstCnt=0
loop=0
loopLen=0
loopCnt=0
remain=0
remainCnt=0

induces=[ -1 for _ in range(M+1)]

for n in range(1,M+1):
	cur = ( tmp ** 2 ) % M
	if induces[ cur ] != -1:
		index = induces[ cur ]
		first = sum(A[:index])
		firstCnt = len(A[:index])
		loop = sum(A[index:])
		loopLen = len(A[index:])
		loopCnt = (N-firstCnt)//loopLen
		remainCnt = (N-firstCnt)%loopLen
		remain = sum(A[index:index+remainCnt])

		# print(first,firstCnt,loop,loopLen,loopCnt,remainCnt,remain)
		# print(cur, induces[ cur ], A[:induces[ cur ]], A[induces[ cur ]:])
		break
	induces[ cur ] = n
	A.append( cur )
	tmp = cur

ans = first + loop * loopCnt + remain
print( ans )

Submission status: Accepted

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


A = [-1]*(M+100)
A[0] = X
i = 0
tmpans = 0
flag = False
check = [-1]*(M+1)
slice = -1
while i< N-1:
    newa = A[i]**2%M
    i+= 1
    if check[newa] != -1:
        flag = True
        slice = check[newa]
        break
    A[i] = newa
    check[newa] = i

if not flag:
    print(sum(A[:i+1]))

else:
    print(sum(A[:slice])+ sum(A[slice:i])*((N-slice)//(i-slice))+sum(A[slice:slice + (N-slice)%(i-slice)]))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
#Python Competetive Programming Template

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):
		#print("a:", a)
		count += 1
		total += a
		if a in d:
			break
		d[a] = (count, total)
		a = (a**2)%m
	else:
		print(total)
	if count != n:
		#print(d)
		looplength = count - d[a][0]
		#print("looplength:", looplength)
		loopsize = total - d[a][1]
		#print("loopsize:", loopsize)
		loopstodo = (n-count)//looplength
		total += loopstodo * loopsize
		count += loopstodo * looplength
		while count < n:
			a = (a**2)%m
			#print("a:", a)
			count += 1
			total += a
		#print(count)
		print(total)

main()

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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


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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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())
    # A = [0] * (M)
    # A[X] = 1
    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)
    # print(now, loop)
    if loop == -1:
        print(sum(now))
    else:
        ans = sum(now[:loop])
        N -= loop
        # print(N)
        SUM = sum(now[loop:])
        ans += (N // (len(now)-loop)) * SUM
        N %= len(now)-loop
        # print(N)
        ans += sum(now[loop:loop+N])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
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:
            #d[cur]----i cycle
            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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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
        #print(tsugi)
        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])
            #print(kaisuu, bangou, loop)
            break
    #print(inlis)
    if kaisuu == 0:
        print(sum(inlis))
    else:
        #print(loop, n, bangou)
        loopnum = (n - bangou) // loop
        amari = (n - bangou) % loop
        if amari > 0:
            #print(inlis[:bangou],loopnum,inlis[bangou:-1],inlis[bangou:bangou+amari])
            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()