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:
import sys

def main():
    N, X, M = map(int, sys.stdin.readline().rstrip().split())

    S = [0] * M  # 何回目に来たか
    C = [0] * M  # 最初にたどり着いたときの値

    _sum = 0
    cycle_sum = 0
    cycle_count = 0
    for i in range(1, N+1):
        _sum += X
        if S[X] == 0:
            C[X] = _sum
            S[X] = i
        else:
            cycle_sum = _sum - C[X]
            cycle_count = i - S[X]
            break
        X = X**2 % M
    else:
        print(_sum)
        return        

    # print(X, S[X], C[X])
    first_sum = C[X]
    loop = (N - S[X]) // cycle_count
    loop_sum = loop * cycle_sum
    _sum = first_sum + loop_sum
    rest = (N - S[X] + 1)  % cycle_count
    # print(first_sum, loop, cycle_count,cycle_sum, loop_sum, rest)
    # print(X)

    for i in range(rest):
        _sum += X
        X = X**2 % M
    
    print(_sum)


main()

Submission status: Wrong Answer

Solution code:
li = list(map(int,input().split()))
n = li[0]
x = li[1]
m = li[2]
li2 = list()
li2.append(x)
z = x
tmp = -1

for i in range(n):
    z = (z*z)%m
    if(z == 0):
        break
    if(z in li2):
        tmp = li2.index(z)
        break
    else:
        li2.append(z)

if(tmp == -1):
    print(sum(li2))
else:
    nagasa = len(li2[tmp:])
    kekka = sum(li2)
    n = n - len(li2)
    q , mod = divmod(n,nagasa)
    kekka = kekka + sum(li2[tmp:])*q
    if(mod!=0):
        end = tmp+mod
        kekka = kekka + sum(li2[tmp:end])
    print(kekka)

Submission status: Wrong Answer

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

A = X
i = 1
sigma = X
A_list = [None, X]
A_sigma = [None, X]
A_index = {X: 1}
cycled = False
while i < N:
    A = A*A % M
    i += 1

    if cycled or A not in A_index:
        sigma += A
        A_list.append(A)
        A_sigma.append(sigma)
        A_index[A] = i

    else:
        cycle_len = i - A_index[A]
        cycles = (N-i) // cycle_len
        sigma += (sigma - A_sigma[A_index[A]]) * cycles
        i += cycles * cycle_len
        cycled = True

print(sigma)

Submission status: Wrong Answer

Solution code:
import sys
N , X , M = map(int,input().split())
flag = [0]*M
S = X
SN = [0]*(M+1)
SN[1] = X 
A = X
if X == 0:
  print(0)
  sys.exit()
if A%M == (A**2)%M:
  print(A*N)
  sys.exit()
loop = 1
flag[X%M] = 1
for i in range(N - 1):
  A = (A**2)%M
  if flag[A] == 0:
    flag[A] = loop
  else:
    loops = flag[A]
    break
  S += A
  SN[loop+1] = S
  loop += 1
if loop <N:
  ans = 0
  ans += SN[loops]
  dS = SN[loop] - SN[loops]
  dl = loop - loops
  ans += ((N-loops)//dl)*dS
  ans += SN[(N-loops)%dl+loops] - SN[loops]
  print(ans)
else:
  print(S)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

readline = sys.stdin.readline

n, x, m = map(int, input().split())
l = np.full(m+1,-1)
l[0] = x
s = set()
s.add(x)
lsum = [-1 for i in range(m+1)]
lsum[0] = x
for i in range(1,m+1):
    a = pow(int(l[i-1]),2,m)
    if a in s:
        if n <= i:
            print(lsum[n-1])
            sys.exit()
        j = np.where(l==a)[0][0]
        ans = lsum[i-1]
        n -= i
        ans += (lsum[i-1] - lsum[j-1]) * (n//(i-j))
        if n % (i-j) == 0:
            print(ans)
            sys.exit()
        else:
            d = n % (i-j)
            ans += lsum[j+d-1] - lsum[j-1]
            print(ans)
            sys.exit()
    else:
        s.add(a)
        l[i] = a
        lsum[i] = lsum[i-1] + a

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
res = 0
ls = []
for i in range(n):
    res += x

    x = x ** 2 % m
    # print(x)
    if len(ls) > 1 and ls[1] == x:
        # print(i, n - i)
        ls = ls[1:]
        sumls = sum(ls)
        res += sumls * ((n - i) // len(ls))
        # print(sum(ls[:(n-i) % len(ls)-1]))
        # print(sum(ls[:(n-i) % len(ls)]))
        res += sum(ls[:(n-i) % len(ls)-1])
        break

    ls += [x]

print(res)
# print(ls)

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-1)
        for j in range(ind, ind+a-1):
            s += note[j]
        print(s)
        exit()
    s += a
    if a == 0:
        break

print(s)

Submission status: Wrong Answer

Solution code:
line = input().split()
line = [int(a) for a in line]

ans = line[1]
num = line[1]
for i in range(line[0]-1):
  num = num%line[2]
  num = (num*num)%line[2]
  ans+=num
  print(num)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n, x, m = map(int, input().split())
d = defaultdict(lambda: False)
length = 0
ans = 0
a = x
memo = [0]
while length<n:
  length = length + 1
  ans = ans + a
  memo.append(ans)
  a = a**2
  if a >= m:
    a = a % m
    if d[a] == True:
      q = n//length
      r = n%length
      ans = ans * q + memo[r]
      break
    elif d[a] == False:
      d[a] = True
      
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 = 0
loop_length = -1

for i in range(N):
    first_sum += A[i]
    A[i+1] = A[i]**2 % M
    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
        # 残りをループで足していく
        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())

lis=[0]*m

ans=x
ai=x
lis[ai]=[1,ans]
flg=0

for i in range(2,n+1):
    ai=(ai**2)%m
    if lis[ai]!=0:
        start=lis[ai][0]
        goal=i-1
        span=goal-start+1
        sumspan=ans-lis[ai][1]+ai
        flg=1
        break
    ans+=ai
    lis[ai]=[i,ans]

if flg:
    times=(n-goal)//span
    last=(n-goal)%span
    ans+=sumspan*times
    #print(last)
    #print(sumspan*times)
    for i in range(0,last-1):
        ans+=ai
        #print(i)
        ai=(ai**2)%m
        if i == last-2:
            ans+=ai
    print(ans)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, X, M = [int(x) for x in input().split()]
s = [0] * (M+10)
s[1] = X
d = {X: 0}
tmp = X
for i in range(M):
    tmp = tmp * tmp % M
    if tmp == 0:
        print(s[i+1])
        exit()
    elif tmp in d:
        l, r = d[tmp], i+1
        s1 = s[l]
        sl = s[r] - s1
        loop = r-l
        ans = sl*((N-l+1)//loop) + s[(N-l+1)%loop+1]
        print(ans)
        exit()
    else:
        d[tmp] = i+1
        s[i+2] = s[i+1] + tmp
print(d)

Submission status: Wrong Answer

Solution code:
n, x, m = map(int,input().split())
k = (x ** 2) % m
l = [0] * (m+1)
l[(x ** 2) % m] == 0
a = [x]
flag = True
for i in range(n-1):
    x = (x ** 2) % m
    a.append(x)
    if l[x] != 0:
        flag = False
        break
    else:
        l[x] += 1
    
    

if not flag:
    p = i
    f = False
    loops = []
    for i in range(len(a)-1):
        if f:
            loops.append(a[i])
        else:
            if (a[i]) == a[-1]:
                loops.append(a[i])
                p = len(a) - (i+1)
                f = True
    k = max(1, len(loops))
    w = (n - p) // k
    x = (n - p - 2) % k


if flag:
    ans = sum(a)
else:
    sss = 0
    for i in range(x):
        sss += loops[i]
    ans = sum(a) - a[-1] + sum(loops) * w + sss
print(ans)

Submission status: Wrong Answer

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

ans = [x]
before = x

for i in range(n-1):
    new = (before ** 2) % m
    before = new
    ans.append(new)
print(ans)

Submission status: Wrong Answer

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]
  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
  s += l[i]
  d[l[i]] = i
print(s)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

readline = sys.stdin.readline

n, x, m = map(int, input().split())
l = np.full(m+1,-1)
l[0] = x
s = set()
s.add(x)
lsum = [-1 for i in range(m+1)]
lsum[0] = x
for i in range(1,m+2):
    a = pow(int(l[i-1]),2,m)
    if a in s:
        if n < i:
            print(lsum[n-1])
            sys.exit()
        j = np.where(l==a)[0][0]
        ans = lsum[i-1]
        n -= i
        ans += (lsum[i-1] - lsum[j-1]) * (n//(i-j))
        if n % (i-j) == 0:
            print(ans)
            sys.exit()
        else:
            d = n % (i-j)
            ans += lsum[j+d-1] - lsum[j-1]
            print(ans)
            sys.exit()
    else:
        s.add(a)
        l[i] = a
        lsum[i] = lsum[i-1] + a

Submission status: Wrong Answer

Solution code:
N,X,M = map(int,input().split())
ans = X
d = [X]
for i in range(N-1):
    val = pow(d[i],2,M)
    ans += val
    d.append(val)
    if val == 0:
        break
    if val == 1:
        ans += N-i-1
        break
    if i % 1000000 == 0:
        print(i,val)
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):
    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 = (int(x) for x in input().split())
dic = {}
count = 1
dic[x]=0
ans = [x]
bool = True
while (count < n):
    x = pow(x, 2, m)
    if x not in dic:
        dic[x] = count
        ans.append(ans[count-1] + x)
    else:
        # print(dic[x])
        # print(count)

        aida = ans[dic[x]:count]
        saisyuutekinakotae = ans[dic[x]-1]
        # print(saisyuutekinakotae)
        for i in range(len(aida)):
            aida[i]-=ans[dic[x]-1]
        # print(aida)
        nokottakosuu = n-dic[x]
        # print(nokottakosuu)
        syuukisuu = nokottakosuu//len(aida)
        # print(syuukisuu)
        hasuu = nokottakosuu%len(aida)
        # print(hasuu)
        saisyuutekinakotae += syuukisuu*aida[-1]
        saisyuutekinakotae += sum(aida[:hasuu])
        print(saisyuutekinakotae)
        bool = False
        count = pow(10, 13)
    count+=1
if bool:
    print(ans[n-1])

Submission status: Wrong Answer

Solution code:
n,x,m=map(int, input().split())
a = x
ans = a
l=[a]
lp=0

for i in range(1,n):
    tmp=(a*a)%m
    a=tmp  
    ans+=tmp
    if a in l:
        lp = l.index(a)
        break
    else:
        l.append(a)

if lp != 0:
    l2 = l[lp:]
    tmp = sum(l2)
    b=int((n-len(l))/len(l2))
    c=(n-len(l))%len(l2)
    ans+=b*tmp+sum(l2[:c])-l2[0]
 
print(ans)

Submission status: Wrong Answer

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

ans = []
before = x

for i in range(n-1):
    new = (before ** 2) % m
    before = new
    ans.append(new)

print(sum(ans))

Submission status: Wrong Answer

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

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

for i in range(1,N):
  l+=[(l[i-1]**2)%M]
  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
  s += l[i]
  d[l[i]] = i
print(s)

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-index)//(p - index)
        roopamari = (N-index)%(p - index)
        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:
# # Make IO faster
# import sys
# input = sys.stdin.readline

# # get single (or) multiple str
# X = input()

# # get single int
# N = int(input())
# # get multiple int (e.g., 2)
# X, Y = map(int, input().split())
# # get multiple int (e.g., 2) for N lines
# XY = [list(map(int, input().split())) for _ in range(N)]

# from IPython import embed; embed(); exit();

# 全部入り
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, bisect_right
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
import numpy as np
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, X, M = list(MAP())
A = set()
A.add(X)
B = [X]
# print(X)
pos = None
for i in range(N - 1):
    a = B[i] * B[i] % M
    if a not in A:
        A.add(a)
        B.append(a)
    else:
        pos = B.index(a)
        break

if pos:
    ans = sum(B[:pos])
    step = (i + 1) - pos
    rep = B[pos:i+1]


    quotient = (N - pos) // step
    remainder = (N - pos) % step
    # print(ans, pos, step, rep, quotient, remainder)

    ans += quotient * sum(rep)
    ans += sum(rep[:remainder])
else:
    ans = sum(B)
print(ans)

Submission status: Wrong Answer

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


main()

Submission status: Wrong Answer

Solution code:

def f(a, n, m):
    return pow(a, 2, m)


def sigma(func, frm, to, mod):
    result = frm
    before = frm
    for i in range(frm, to+1):
        before = func(before, i, mod)
        result += before

        print(i, before)

    return result


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

print(sigma(f, X, N, M))

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
def am(a, b):
    return (a * a) % b
l = {x}
u = []
now = x
for i in range(n):
    s = am(now, m)
    if(s in l):
        break
    l.add(s)
    now = s
c = list(l).index(s)
if(0 in l):
    print(sum(l))
else:
    for i in range(c):
        u.append(l.pop())
    a = (n-len(u)) // len(l)
    b = (n-len(u)) % len(l)
    print(sum(u) + a * sum(list(l)) + sum(list(l)[:b]))