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;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define drep(i,n) for(int i = (n-1); i >= 0; i--)
#define all(v) (v).begin(),(v).end()
#define maxs(x,y) (x = max(x,y))
#define mins(x,y) (x = min(x,y))
template <class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; }
template <class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; }
template <class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template <class T> T lcm(T a, T b) { return a/gcd(a,b)*b; }
typedef pair<int, int> P;
typedef long long ll;
const int INF = 1001001001;
const ll LINF = 1001002003004005006ll;
const ll MOD = 1e9+7;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
	ll n;
    int x, m;
	cin >> n >> x >> m;
    vector<ll> cum(m+1), num(m+1);
    cum[0] = x;
    num[x] = 1;
    ll now = x;
    int i = 1;
    int pre_num, cycle_num, pre_sum, cycle_sum;
    while(1) {
        now = (now*now)%m;
        // cout << i << ' ' << now << endl;
        if(num[now]!=0) {
            pre_num = num[now]-1;
            cycle_num = i - pre_num;
            pre_sum = cum[pre_num-1];
            cycle_sum = cum[i-1] - pre_sum;
            // cout << pre_num << ' ' << pre_sum << ' ' << cycle_num << ' ' << cycle_sum << ' ' << endl;
            break;
        }
        num[now] = i+1;
        cum[i] = cum[i-1] + now;
        ++i;
    }
    ll ans = 0;
    if(n<pre_num) {
        ans = cum[n-n];
    } else {
        ans += pre_sum;
        n -= pre_num;
        ans += (n/cycle_num) * cycle_sum;
        n %= cycle_num;
        ans += cum[n + pre_num - 1] - pre_sum;
    }
    cout << ans << endl;
	return 0;
}