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<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int cmp1(const void *p,const void *q)//昇順
{
    return *(int *)p - *(int *)q;
}

typedef long long int int64;

int main()
{
    int64 n;
    int64 x,m;
    int64 i=1;
    int64 num=0;
    int roopflag=0;
    int modmap[100010]={0};
    int64 modsum[100010]={0};
    int64 roop,roopnum,rest;
    int64 ans=0;
    scanf("%lld %lld %lld",&n,&x,&m);

    num=x%m;
    modmap[num]=1;
    modsum[1]=num;
    ans+=num;

    while(i<n)
    {
        i++; //今からi回目
        num=(num*num)%m;
        if(roopflag==1)
        {
            ans+=num;
        }
        else if(modmap[num]==0)
        {
            modmap[num]=i;
            modsum[i]=(modsum[i-1]+num);
            ans+=num;
        }
        else //ループ発見
        {
            roop=i-modmap[num];
            roopnum=(n-i+1)/roop;
            //rest=(n-i)%roop;

            ans+=(modsum[i-1]-modsum[i-roop-1])*(roopnum);
            //printf("i:%lld\n",i);
            //printf("roop:%lld roopnum:%lld\n",roop,roopnum);
            num=modsum[i-1]-modsum[i-2];//numはroopの終端
            i+=(roop*roopnum-1);
            roopflag=1;
        }
        //printf("A_%lld = %lld sum=%lld\n",i,num,ans);
    }

    printf("%lld",ans);
}