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: Accepted)

#include <bits/stdc++.h>

#define fst first
#define snd second
#define ll long long
#define ld long double
#define pb push_back
#define emp emplace_back
#define pii pair<int, int>
#define usg unsigned
#define sg signed
#define mp make_pair

using namespace std;

void setIO(){
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	// freopen("input.txt", "r", stdin);
	// freopen("output.txt", "w", stdout);
}

const ld PI = 4*atan((ld)1);
const int INF = 1e9+7;
const ll _INF = 1e18+7;

set<ll>st;
vector<ll>lp;
ll n, x, m, sum, y;

int main(){
	setIO();
	cin >> n >> x >> m;
	y = x;
	st.insert(x);
	for (int i = 0; i <= m; i++){
		x = (x*x)%m;
		if (st.count(x))
			break;
		st.insert(x);
	}
	lp.emp(x); ll z = (x*x)%m, lsum = x;
	while (z != x){
		lsum += z;
		lp.emp(z);
		z = (z*z)%m;
	}
	for (int i = 1; i <= n; i++){
		if (y == x){
			ll loop = (n-i+1)%(int)lp.size(), summ = 0;
			for (int j = 0; j < loop; j++)
				summ += lp[j];
			cout << sum+summ+(n-i+1)/(int)lp.size()*lsum << endl;
			return 0;
		}
		sum += y;
		y = (y*y)%m;
	}
	cout << sum << endl;
}