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# (Mono-mcs 6.8.0.105) (judge verdict: Accepted)

using System;
using System.Collections.Generic;
class Program
{
	static void Main(string[] args)
	{
		string[] str = Console.ReadLine().Split();
		long N = long.Parse(str[0]);
		int X = int.Parse(str[1]);
		int M = int.Parse(str[2]);
		long[]D = new long[M];
		int[]T = new int[M];
		long[]A = new long[M];
		long ans = 0;
		for(var i=0;i<M;i++){
			T[i] = -1;
		}
		long a = X;
		D[X] = X;
		T[X] = 0;
		A[X] = X;
		ans += X;
		for(var i=1;i<M;i++){
			if(N==1){
				break;
			}
			a = a * a % M;
			ans += a;
			//Console.Error.WriteLine(a+" "+ans);
			if(i+1>=N){
				break;
			}
			if(T[a] == -1){
				D[a] = a;
				T[a] = i;
				A[a] = ans;
			} else {
              	Console.Error.WriteLine(a+" "+ans);
				long T1 = (N-i-1)/(i-T[a]);
              	Console.Error.WriteLine(i+" "+T1+" "+T[a]);
				ans += T1 * (ans - A[a]);
				long i2 = i + (N-i-1)/(i-T[a])*(i-T[a]);
             	Console.Error.WriteLine(i2+" "+(N-i-1)+" "+(i-T[a])+" "+T1);
				for(long j=i2+1;j<N;j++){
					a = a * a % M;
					ans += a;
				}
				break;
			}
			if(i+1>=N){
				break;
			}
		}
		Console.WriteLine(ans);
	}
}