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:
n, x, m = map(int, input().split())

a = [x]
b = [x]
rabbit = x
turtle = x
flag = False

start = 0
end = 1

while True:
  rabbit = (rabbit ** 2) % m
  rabbit = (rabbit ** 2) % m
  turtle = (turtle ** 2) % m
  a.append(turtle)
  b.append(b[-1] + turtle)
  
  if rabbit == turtle:
    break

if len(a) >= n:
  print(b[n - 1])
elif rabbit == 0:
  print(b[-1])
else:
  rabbit = x
  while rabbit != turtle:
    rabbit = (rabbit ** 2) % m
    turtle = (turtle ** 2) % m
    start += 1
    a.append(turtle)
    b.append(b[-1] + turtle)

  turtle = (turtle ** 2) % m
  end = start + 1
  b.append(b[-1] + turtle)
  while rabbit != turtle:
    turtle = (turtle ** 2) % m
    end += 1
    a.append(turtle)
    b.append(b[-1] + turtle)

  if len(a) >= n:
    print(b[n - 1])
  elif a[-1] == 0:
    print(b[-1])
  else:
    ans = b[start - 1]
    ans += (b[end - 1] - b[start - 1]) * ((n - start) // (end - start))
    if (n - start) % (end - start) != 0:
      ans += b[((n - start) % (end - start)) + start - 1] - b[start - 1]
    print(ans)

Submission status: Wrong Answer

Solution code:
S=list(map(int,input().split()))
a=[S[1]]
for i in range(0,S[0]-1):
        a.append(((a[i]**2)%(10**9+7))%S[2])
print(sum(a))

Submission status: Wrong Answer

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

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

print(s)

Submission status: Wrong Answer

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

m = [X]
s = X

for i in range(1, N):
    a = (m[i-1]%M)**2
    if a == m[0]:
        break
    elif a == 0:
        print(sum(m))
        exit()
    m.append(a)
ans = sum(m)*(N//len(m))
for i in range(N - (N//len(m))*len(m)):
    ans += m[i]
print(ans)

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:
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(x)
        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-1
        kekka = kekka + sum(li2[tmp:end])
    print(kekka)

Submission status: Wrong Answer

Solution code:
N,X,M=map(int,input().split())
ans=0
last=[-1]*(M)
A=[X]
last[X]=0
i=1
while i<N:
    T=pow(A[-1],2,M)
    A.append(T)
    if last[T]!=-1:
        Roop=len(A)-last[T]-1
        Left,Right=last[T],i
        break
    last[T]=i
    i+=1


if i==N:
    print(sum(A))
    exit()
X=A[i]
#ループまでがA[i]

#ループ中の和
Sum=0

for i in range(Left,Right):
    Sum+=A[i]
rest=N-i-1
ans+=sum(A)
ans+=(rest//(Right-Left)*Sum)

#ループ後の和
X=X**2%M
for i in range(rest%Roop-1):
    ans+=X
    X=X**2%M
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
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:
    ans += ruiseki[k-2]
    ans += ((N-k+1)//(loop))*loop_v
    l = (N-k+1)%loop
    ans += ruiseki[k+l-2] - ruiseki[k-2]
else :
    ans = ruiseki[-1]

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

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

Submission status: Wrong Answer

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

ans = 0
chck = 0
lst = [X]
for i in range(N):
    X = (X**2)%M

    if i >= 2:
        if X == lst[2]:
            T = i-1
            chck = 1
            break

    lst.append(X)

    if X == 0:
        break

if chck:
    p = N//T
    q = N%T
    ans = sum(lst[2:])*p + sum(lst[:q])

else:
    ans = sum(lst)

print(ans)

Submission status: Wrong Answer

Solution code:
N, X, M = map(int, input().split())
a = [0 for i in range(M+1)]
b = [X]
a[X-1] = 1

for i in range(min(N-1, M)):
  X = X**2%M
  a[X-1] += 1
  b.append(X)
  if a[X-1] > 1:
    break

if len(b) == N:
  print(sum(b))

else:
  ls = b.index(b[-1])
  print(b)
  bloop = b[ls:-1]
  ans = 0
  if ls > 0:
    for i in range(ls):
      ans += b[i]
  loop = (N-ls)//len(bloop)
  ans += sum(bloop) * loop
  if (N-ls)%len(bloop) != 0:
    for i in range((N-ls)%len(bloop)):
      ans += bloop[i]
  print(ans)

Submission status: Wrong Answer

Solution code:
import sys

def solve():
      input = sys.stdin.readline
      N, X, M = map(int, input().split())
      D = [False] * M
      roopStart = -1
      now = X
      for i in range(M): #ループ検出
            ne = now * now % M
            if D[ne]:
                  roopStart = ne
                  break
            else: 
                  D[ne] = True
                  now = ne
      
      roopL, roopS = 1, 0
      now = roopStart
      for i in range(M):
            ne = now * now % M
            roopS += now
            if ne == roopStart: break
            else: 
                  roopL += 1
                  now = ne

      #初期和
      ans = 0
      initialL = 0
      now = X
      for i in range(M):
            if i == N: break
            if now != roopStart:
                  ans += now
                  initialL += 1
                  now = now * now % M
            else: break
      if initialL <= N:
            N -= initialL
            roopTimes = N // roopL
            roopRem = N % roopL
            ans += (roopTimes * roopS) 
            now = roopStart
            for j in range(roopRem):
                  ans += now
                  now = now * now % M
            
      print(ans)
      return 0

if __name__ == "__main__":
      solve()

Submission status: Wrong Answer

Solution code:
N, X, M = map(int, input().split())
A = X
P = set([A])
cnt, cnt2 = 0, 0
S = A
S2 = 0
off = 0
for i in range(N-1):
    A = A**2%M
    if A in P and cnt == 0:
        cnt = i
        off = A
    elif A ==off:
        cnt2 = i
        break
    S += A
    if cnt != 0:
        S2 += A
    P.add(A)
l = max(cnt2-cnt,1)
res = 0
for i in range((A-cnt-1)%l):
    res += off
    off = off**2%M
res += S + ((N-cnt-1)//l)*S2
print(res)

Submission status: Wrong Answer

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

for i in range(n):
    ans += x
    x = x**2
    if x >= m:
        x = x**2 % m
    if x == 0:
        break

print(ans)

Submission status: Wrong Answer

Solution code:
n,x,m=map(int,input().split())
S=set()
S.add(x)
ans=[x]
l=1
for i in range(min(n,m)):
  if ans[i]**2%m in S:
    break
  else:
    S.add(ans[i]**2%m)
    ans.append(ans[i]**2%m)

l=len(ans)
if l==m:
  p=sum(ans)*(n//m)+sum(ans[:(n%m)])
  exit()
if l<n:
  p=sum(ans)+ans[-1]*(n-l)
else:
  p=sum(ans)
  
print(p)

Submission status: Wrong Answer

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

ans = 0
roop_init = -1
roop_sum = 0
roop_len = 0
x = X
ans += x
flug = False    # 周期を数えるフラグ
for i in range(2, N+1):
    old_x = x
    x = old_x**2 % M
    if x == 0:
        break
    if old_x**2 >= M and not flug:
        # print(old_x, x)
        flug = True
        roop_init = x
        roop_sum = x
        roop_len = 1
    elif x == roop_init and flug:
        # print(i)
        ans += (N - (i-1)) // roop_len * roop_sum
        for j in range((N - (i-1)) % roop_len):
            if j != 0:
                old_x = x
                x = old_x**2 % M
            ans += x
        print(ans)
        break
    elif flug:
        roop_len += 1
        roop_sum += x
    ans += x
else:
    print(ans)

Submission status: Wrong Answer

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

ls = [X]
enc = [0] * M
enc[X] = 1

count = 1

while count < N:
  X *= X
  X = X % M
  count += 1
  if enc[X] == 0:
    enc[X] += 1
    ls.append(X)
  else:
    ls.append(X)
    break

if count == N:
  print(sum(ls))
else:
  first = ls.index(X) + 1
  interval = count - first 
  
  out = sum(ls[:first - 1]) + (N - first + 1) // interval * sum(ls[first - 1:count - 1])
  if (N - first - 1) % interval != 0:
    out += sum(ls[first - 1: first - 1 + (N - first - 1) % interval + 1])

  print(out)

Submission status: Wrong Answer

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

n, x, m = li()

tmp = x
l = [x]
begin = 0
for i in range(1, n):
    p = tmp%m
    q = (p*p)%m
    if (q in l):
        begin = l.index(q)
        break
    l.append(q)
    tmp = q

flen = len(l[begin:])
fsum = sum(l[begin:]) 

ans = 0
if x % m == 0:
    ans = 0
elif l[-1] == 0:
    ans = sum(l)
else:
    ans = n // flen * fsum + sum(l[: n % len(l[begin:])])

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
        if sumspan==1:
            ans-=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)
    ans+=ai
    for i in range(1,last):
        #print(i)
        ai=(ai**2)%m
        ans+=ai
    if last==1:
        ai=(ai**2)%m
        ans+=ai
    print(ans)
else:
    print(ans)

Submission status: Wrong Answer

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

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
        if sumspan==1:
            ans-=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)
    ans+=ai
    for i in range(1,last):
        #print(i)
        ai=(ai**2)%m
        ans+=ai
    if last==1:
        ai=(ai**2)%m
        ans+=ai
    print(ans)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N,x,MOD = map(int, input().split())
s = x
flag = False
if N == 1:
  flag = True
for i in range(1,MOD):
  x = (x*x) % MOD
  s += x
  if N == (i+1):
    flag = True
    break
if flag == True:
  print(s)
else:
  t_s = 0
  cnt = 0
  init = x
  for i in range(MOD):
    x = (x*x) % MOD
    t_s += x
    cnt += 1
    if x == init:
      break
  bi = (N-MOD)//cnt
  res = (N-MOD)%cnt
  s += t_s * bi
  for i in range(res):
    x = (x*x) % MOD
    s += x
  print(s)

Submission status: Wrong Answer

Solution code:
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
# input = sys.stdin.readline 
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()

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

Submission status: Wrong Answer

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

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

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

summation = X
loop_length = -1

for i in range(N-1):
    A[i+1] = A[i]**2 % M
    summation += A[i+1]
    if A[i+1] == 0:
        break
    elif is_seen[A[i+1]]:
        # すでに出現済みということで A[0], ..., A[i] までがループであることがわかる
        loop_length = (i+1) - A.index(A[i+1])
        ind = i
        summation -= A[i+1]
        break
    else:
        is_seen[A[i+1]] = 1

if loop_length != -1:
    # 残りをループで足していく
    A_loop = A[A.index(A[ind+1]):ind+1]
    loop_sum = sum(A_loop)
    res = N - ind  # 足さないといけない残り
    ans = summation + (res//loop_length) * loop_sum
    # はみ出したぶん
    if res % loop_length != 0:
        ans += sum(A_loop[:res%loop_length-1])
else:
    ans = summation

print(ans)

Submission status: Wrong Answer

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]
        #print(ans, i, dic[A][1])
        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)

#if N // cyc >= 2:
#    ans = ans + r * (N // cyc - 1)

ans = t + r * (N//cyc)

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

print(ans)

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+100):
    num=(A[a-1]**2)%m
    if not D[num]:
        A.append(num)
        D[num]=True
    else:
        kkey=num
        break
if n<10**5+100:
    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:
n,x,m=map(int,input().split())
tmp=x
L=[]
for i in range(n):
    tmp=tmp**2%m
    if tmp not in L:
        L.append(tmp)
    else:
        break
if len(L)==1:
    ans=x+L[0]*(n-1)
else:
    times=(n-2)//(len(L)-1)
    loss=(n-2)%(len(L)-1)
    ans=x+L[0]+sum(L[1:])*times
    for i in range(loss):
          ans+=L[i+1]
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline


tm=0
n,x,m=map(int,input().split())
s=0
for i in range(n):
  if i==0:
    s+=x
  else:
    x=x*x
    if x>m:
      x=x%m
    s+=x
print(s)

Submission status: Wrong Answer

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

n, x, m = li()

tmp = x
l = [x]
begin = 0
for i in range(1, n):
    q = (tmp*tmp)%m
    if (q in l):
        begin = l.index(q)
        break
    l.append(q)
    tmp = q

flen = len(l[begin:])
fsum = sum(l[begin:]) 

ans = sum(l) if l[-1] == 0 else n // flen * fsum + sum(l[: n % len(l[begin:])])

print(ans)

Submission status: Wrong Answer

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

A = [X]
Asum = [X]
roopsum = 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)
        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:
n,x,m=map(int, input().split())
d={}
a=[]
ans=x
key=-1
rem=n-1
for i in range(n-1):
    x%=m
    x*=x
    x%=m
    if x in d.keys():
        key=d[x]
        break
    else:
        a.append(x)
        ans+=x
        d[x]=i
        rem-=1
key+=1
if rem:
    to_sum=sum(a[key-1:len(a)])
    ans+=(to_sum)*(rem//(len(a)-key-1))
    rem%=(len(a)-key-1)
    for i in range(key-1, key-1+rem):
        ans+=a[i]
print(ans)
#print(a)

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
        if sumspan==1:
            ans-=1
        break
    ans+=ai
    lis[ai]=[i,ans]

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

Submission status: Wrong Answer

Solution code:
n, x, m = map(int, input().split())
ans = x
cnt = [0] * m
loop = []
start = -1
for i in range(min(n, 3 * m)):
    x = (x * x) % m
    if cnt[x] == 1:
        loop.append(x)
        if start == -1:
            start = i
    cnt[x] += 1
for i in range(m):
    if cnt[i] > 0:
        ans +=  i
l = len(loop)
if l > 0:
    ans += sum(loop) * ((n-1-start) // l - 1)
    ans += sum(loop[:l%m])
print(ans)