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 Java (OpenJDK 11.0.6) (judge verdict: Runtime Error)

import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc =new Scanner(System.in);
    long N =sc.nextLong();
    long ans =0;
    int X =sc.nextInt();
    int M =sc.nextInt();
    long A[] =new long[2*M];
    long B[] =new long[M];
    long C[] =new long[M];
    B[0]=M+1;
    A[0]=X;
    long k =0;
    int m =0;
    int c=0;
    if(N<2*M){
      for(int i=1;i<N;i++){
      A[i]=(A[i-1]*A[i-1])%M;
      if(A[i]<0){A[i]=A[i]+M;}
      if(i>1){
      if(A[i]==A[1]){m=i-1;break;}
      else{k=k+A[i];}}
      else{k=k+A[i];}
      }
      ans =k;
      System.out.println(ans+X);
    }
    else{
    for(int i=1;i<2*M;i++){
      A[i]=(A[i-1]*A[i-1])%M;
      if(A[i]<0){A[i]=A[i]+M;}
      int d =(int)A[i];
      if(B[d]==d){
        c=(int)C[d];
        m=i-1;
        break;
      }
      else{B[d]=d;C[d]=i;}
    }
    long w =(N-c+1)/m;
    long ww =(N-c+1)%m;
      for(int i=0;i<=m;i++){
        if(i<c){ans =ans+A[i];}
        else{k =k+A[i];}
      }
      ans =ans+w*k;
    for(int i=1;i<=ww;i++){
      ans =ans+A[c+i-1];
    }
    System.out.println(ans);
    }
  }
}