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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;

namespace AtCoder
{
    class Program
    {
        private static void Main(string[] args)
        {
            var ss = Scanner.ArrayLong(3);
            var n = ss[0];
            var m = ss[2];
            if (n == 1)
            {
                Console.WriteLine(ss[1]);
                return;
            }

            var a = ss[1];
            if (a == 0)
            {
                Console.WriteLine("0");
                return;
            }
            var looper = new List<long>{a};
            var loopHead = new List<long>();
            var looping = new List<long>();
            for (int i = 0; i < n - 1; i++)
            {
                a = a * a % m;
                if (looper.Contains(a))
                {
                    loopHead = looper.TakeWhile(x => x != a).ToList();
                    looping = looper.SkipWhile(x  => x != a).ToList();
                    looper.Clear();
                    break;
                }
                looper.Add(a);
            }

            if (looper.Count != 0)
            {
                Console.WriteLine(looper.Sum());
                return;
            }
            var sum = loopHead.Sum();
            n -= loopHead.Count;
            if (looping.Count != 0)
            {
                var multiplier = n / looping.Count;
                sum += looping.Sum() * multiplier;
                n %= looping.Count; 
                sum += looping.Take((int)n).Sum();
            }
            
            Console.WriteLine(sum);
        }

        #region Utility
        static readonly StreamScanner Scanner = new StreamScanner(Console.OpenStandardInput());
        #endregion
    }

    
    #region Utility Class
    public class StreamScanner
    {
        public StreamScanner(Stream stream) { str = stream; }
        private readonly Stream str;
        private readonly byte[] buf = new byte[1024];
        private int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        private byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len) {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        public char Char() 
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b; 
        }
        public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public string ScanIncludeSpace()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 32 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        public int Integer() { return (int)Long(); }
        public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
        
        /// <summary> 数値読み込み </summary>
        public List<long> ArrayLong(int count = 0)
        {
            var scan = new List<long>();
            for (int i = 0; i < count; i++)
            {
                scan.Add(Long());
            }
            return scan;
        }
        /// <summary> 数値読み込み </summary>
        public List<int> ArrayInt(int count = 0)
        {
            var scan = new List<int>();
            for (int i = 0; i < count; i++)
            {
                scan.Add(Integer());
            }
            return scan;
        }
    }
    #endregion
    
}