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

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define REP(i,n) for(int i=0,_n=(int)(n);i<_n;++i)
#define ALL(v) (v).begin(),(v).end()
#define CLR(t,v) memset(t,(v),sizeof(t))
template<class T1,class T2>ostream& operator<<(ostream& os,const pair<T1,T2>&a){return os<<"("<<a.first<<","<<a.second<< ")";}
template<class T>void pv(T a,T b){for(T i=a;i!=b;++i)cout<<(*i)<<" ";cout<<endl;}
template<class T>void chmin(T&a,const T&b){if(a>b)a=b;}
template<class T>void chmax(T&a,const T&b){if(a<b)a=b;}

ll nextLong() { ll x; scanf("%lld", &x); return x;}



int main2() {
  ll N = nextLong();
  ll X = nextLong();
  ll M = nextLong();

  ll a = X;

  vector<ll> step(M+10, -1);
  vector<ll> sums(M+10);

  step[a] = 0;
  sums[a] = a;

  ll age = 1;
  ll y;
  ll cycle_len, cycle_sum;
  for (; ; age++) {
    ll na = (a * a) % M;
    if (step[na] != -1) {
      cycle_len = (step[a] + 1) - step[na];
      cycle_sum = (sums[a] + na) - sums[na];
      y = na;
      break;
    } else {
      step[na] = age;
      sums[na] = sums[a] + na;
    }
    a = na;
  }

  if (age >= N) {
    ll ans = 0;
    a = X;
    REP(_, N) {
      ans += a;
      a = (a * a) % M;
    }
    cout << ans << endl;
    return 0;
  }

  ll ans = 0;
  ans += sums[y];
  N -= step[y];

  ll C = N / cycle_len;
  N -= C * cycle_len;
  ans += C * cycle_sum;
  {
    a = y;
    REP(_, N) {
      ans += a;
      a = (a * a) % M;
    }
  }
  cout << ans << endl;
  return 0;
}

int main() {

#ifdef LOCAL
  for (;!cin.eof();cin>>ws)
#endif
    main2();
  return 0;
}