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 in Ruby (2.7.1) (judge verdict: Time Limit Exceeded)

N,X,M = gets.chomp.split.map(&:to_i)
an = X
ans = 0
s = 0
ss = 0
count = 0
countcount = 0
kokomade = 0
kokomademade = 0
ppp = 0

(1..N).each do |i|
  if i == 1
  	anan = an % M
  else
  	anan = (an**2 % M)
    if anan == 0
      puts ans
      exit
    elsif anan == s
      ans += (ans - kokomade) * ((N - i + 1) / (i - count))
      add = ((N - i + 1) % (i - count))
      (1..add).each do |j|
        ans += anan
        ananan = anan**2 % M
        anan = ananan
      end
      puts ans
      exit
    elsif anan == ss
      ans += (ans - kokomademade) * ((N - i + 1) / (i - countcount))
      add = ((N - i + 1) % (i - countcount))
      (1..add).each do |j|
        ans += anan
        ananan = anan**2 % M
        anan = ananan
      end
      puts ans
      exit
    end
  end
  if an**2 > M && ppp == 0
    s = anan
    kokomade = ans
    count = i
    ppp += 1
  end
  if i > 20 && ppp == 1
    ss = anan
    kokomademade = ans
    countcount = i
    ppp += 1
  end
  ans += anan
  an = anan
end

puts ans