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 <iostream>
using namespace std;
#define fi first
#define se second
#define ll long long int
#define pb push_back
int main(){
    ll n, x, m, bef, cur;
    cin>>n>>x>>m;
    if (n==0){
        cout<<0<<endl;
        return 0;
    }
    ll par[2*m+1];
    pair <ll, ll> arr[2*m+1]; // fi for sum, se for the number of iterations needed to arrive there
    for (ll i=0; i<=m; i++) arr[i].fi=0, arr[i].se=-1;
    arr[x].fi=x, arr[x].se=1, bef=x, par[x]=0, par[0]=0, arr[0].fi=0;
    for (ll i=1; i<n; i++){
        cur=(bef*bef)%m;
        if (arr[cur].se==-1){
            arr[cur].se=arr[bef].se+1;
            arr[cur].fi=arr[bef].fi+cur;
            par[cur]=bef;
        }
        else {
            ll l=cur, r=bef;
            ll cnt=n;
            ll ans=0;
            cnt-=arr[l].se, ans+=arr[l].fi;
            ans+=cnt/(arr[r].se-arr[l].se+1)*(arr[r].fi-arr[par[l]].fi), cnt-=cnt/(arr[r].se-arr[l].se+1)*(arr[r].se-arr[l].se+1);
            if (cnt!=0){
                for (ll j=1; j<=m; j++){
                    if (arr[j].se==arr[l].se+cnt){
                        ans+=arr[j].fi-arr[l].fi;
                        break;
                    }
                }
            }
            cout<<ans<<endl;
            return 0;
        }
        bef=cur;
    }
    cout<<arr[cur].fi<<endl;
}