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# (.NET Core 3.1.201) (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;
using static Scanner;

class Program
{
    public static void Main()
    {
        long n = ReadLong();
        long x = ReadLong();
        long m = ReadLong();

        var a = new List<long>() { x };
        var s = new List<long>() { 0, x };
        var c = new Dictionary<long, int>() { { x, 0 } };
        for (int i = 1; i < n; i++)
        {
            long next = a[^1] * a[^1] % m;

            if (c.ContainsKey(next))
            {
                long k = s[c[next]];
                long ans = k;
                n -= c[next];
                long len = i - c[next];
                ans += n / len * (s[^1] - k);
                ans += s[(int)(c[next] + (n % len))] - k;
                Console.WriteLine(ans);
                return;
            }

            a.Add(next);
            s.Add(s[^1] + next);
            c[next] = i;
        }
        Console.WriteLine(s[^1]);
    }
}

static class Scanner
{
    static Queue<string> que = new Queue<string>();
    public static string Read() { if (!que.Any()) foreach (var s in Console.ReadLine().Split()) que.Enqueue(s); return que.Dequeue(); }
    public static int ReadInt() => int.Parse(Read());
    public static long ReadLong() => long.Parse(Read());
    public static IEnumerable<string> Read(long n) { for (long i = 0; i < n; i++) yield return Read(); }
    public static IEnumerable<int> ReadInt(long n) => Read(n).Select(int.Parse);
    public static IEnumerable<long> ReadLong(long n) => Read(n).Select(long.Parse);
}