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 C++ (GCC 9.2.1) (judge verdict: Runtime Error)

#include <bits/stdc++.h>
using namespace std;
int main() {
  // 入力
  long long N, X, M, Sum_A = 0;
  cin >> N >> X >> M;
  
  // 数列{A_n}
  vector<long> A(M+1, 0);
  A.at(1) = X;
  for (int i = 2; i <= M; i++) {
    A.at(i) = (A.at(i-1)*A.at(i-1))%M;
  }
  
  // 循環節があるか確認
  int nagasa = 0, hajime;
  for (int i = 1; i < M; i++) {
    if (A.at(M-i) == A.at(M)) {  // A_{1~M-1}のうちA_Mと同じで最も近いもの
      nagasa = i;  // 循環節の最小の長さ
    }
    if (nagasa == i) {
      for (int j = 1; j <= M-i; j++) {
        if (A.at(j) == A.at(M)) {  // A_{1~M-1}のうちA_Mと同じで最も遠いもの
          hajime = j-1;  // 循環節1節目のうちA_Mと同じものの添え字
          break;  //ループを抜ける
        }
      }
    }
    if (nagasa == i) {
      break;  //ループを抜ける
    }
  }
  
  // 循環しない場合
  if (nagasa == 0) {
    for (int i = 0; i < 2*N; i++) {
      Sum_A += A.at(i);
    }
  }
  
  // 循環する場合
  else {
    int shou, amari;
    shou = (N-hajime)/nagasa;  // 循環節の数-(0or1)
    amari = hajime + (N-hajime)%nagasa;  // 循環節(or2節目)にたどり着くまで
    
    // 循環節の部分の和
    for (int i = M-nagasa; i < M; i++) {
      Sum_A += A.at(i) * shou;
    }
    
    // 循環節にたどり着くまでの和
    for (int i = 0; i <= amari; i++) {
      Sum_A += A.at(i);
    }
  }
  
  // 出力
  cout << Sum_A << endl;
}