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;
#define ll long long int
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define FORit(it,a) for(auto it=a.begin();it!=a.end();it++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
#define vec vector
#define vi vec<int>
#define vll vec<ll>
#define pb push_back
#define pp pop_back
#define all(x) x.begin(),x.end()
#define testcases ll t;cin>>t;while(t--)
#define mem(a,k) memset(a,k,sizeof(a))
#define FF first
#define SS second
#define MP(x,y) make_pair(x,y)
#define rt return
#define br break
#define ct continue
#define elif else if
#define ii pair<int,int>
#define vecin(a,n,index) for(int i=index;i<n;i++)cin>>a[i]
#define vecout(a,n,index) for(int i=index;i<n;i++)cout<<a[i]<<" ";cout<<endl;
//ll mod = 1000000007;
ll a[100001] = {0};
ll n, x, m;
void fun() {

	cin >> n >> x >> m;
	a[1] = x;
	FOR(i, 2, 100001)a[i] = (a[i - 1] % m * a[i - 1] % m) % m;
}
void solve() {
	fun();
	map<ll, ll> visited;
	vll ns;
	vll cs;
	ll tmp = 0;
	FOR(i, 1, m + 1) {
		if (visited[a[i]] == 1) {
			tmp = a[i];
			br;
		}
		else {
			ns.pb(a[i]);
			visited[a[i]] = 1;
		}
	}
	FOR(i, 0, ns.size()) {
		if (ns[i] == tmp) {
			FOR(j, i, ns.size())cs.pb(ns[j]);
			int k = ns.size() - i;
			while (k--)ns.pp();
		}
	}
	vll nsum(ns.size()); vll csum(cs.size());
	partial_sum(all(ns), nsum.begin());
	partial_sum(all(cs), csum.begin());
	// we have sum both normal and cycle sum seq
	//
	ll ans = 0, mine;
	if (n > ns.size())mine = ns.size(); else mine = n;
	ans += nsum[mine - 1];
	n = n - mine;
	if (n) /*if(!n) Means if(n==0)*/
	{
		ll p = n / cs.size(), rem = n % cs.size();
		ans += (csum[csum.size() - 1] * p);
		if (rem)
			ans += (csum[rem - 1]);

	}
	cout << ans << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	ios_base::sync_with_stdio(false);	cin.tie(NULL);	cout.tie(NULL);
	// START FROM HERE :)
	solve();
}