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: Wrong Answer)

line = gets.split(' ').map(&:to_i)

N = line[0]
X = line[1]
M = line[2]
Inf = 10**10

seq = [X]
for i in 2..M * 2 do
  seq[i-1] = (seq[i-2] ** 2) % M
end

res_deja = []
for i in 1..M do
  res_deja[i-1] = false
end

for i in 1..2*M do
  num = seq[i-1]
  if num >= M then
  elsif res_deja[num-1] then
    rep_end_id = i-2     #it must've ended in the previous time.
    rep_end_num = seq[i-1]
    break
  else
    res_deja[num-1] = true
  end
end
    
for i in 1..2*M do
  if seq[i-1] == rep_end_num then
    rep_start_id = i-1
    break
  end
end
  
rep_int = rep_end_id - rep_start_id + 1

loop_sum = 0
for i in rep_start_id..rep_end_id do
  loop_sum += seq[i]
end

if N - rep_start_id + 1 >= 0 then
  num_loop = (N - rep_start_id + 1) / rep_int
else
  num_loop = 0
end
before_loop_id = rep_start_id - 1
after_loop_id = rep_start_id + num_loop * rep_int
  
before_loop_sum = 0
for i in 0..before_loop_id do
  before_loop_sum += seq[i]
end

after_loop_sum = 0
for i in rep_start_id..(rep_start_id + (N - after_loop_id - 1)) do
  after_loop_sum += seq[i]
end

if num_loop == 0 then
  puts before_loop_sum
else
  puts before_loop_sum + loop_sum * num_loop + after_loop_sum
end