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 Go (1.14.1) (judge verdict: Accepted)

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int) []int {
	ret := make([]int, N)
	for i := 0; i < N; i++ {
		ret[i] = getInt()
	}
	return ret
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func small(N, X, M int) {
	a := X
	ans := X
	for i := 2; i <= N; i++ {
		a *= a
		a %= M
		ans += a
	}
	out(ans)
}

type countMod struct {
	mod int
	m   []int
	pat []int
	sum int
}

func newCounter(n, mod int) *countMod {
	var ret countMod
	ret.mod = mod
	ret.m = make([]int, mod)
	ret.pat = make([]int, 0)
	ret.sum = 0
	return &ret
}

func (c *countMod) append(v, N int) (int, bool) {
	// a := v % c.mod
	a := v
	if c.m[a] == 0 {
		c.m[a]++
		c.pat = append(c.pat, a)
		c.sum += a
		if len(c.pat) == N {
			return c.sum, true
		}
		return c.sum, false
	}
	start := 0
	ret := 0
	tot := c.sum
	for i := 0; i < len(c.pat); i++ {
		if c.pat[i] == a {
			start = i
			break
		}
		ret += c.pat[i]
		tot -= c.pat[i]
	}
	N -= start
	loop := len(c.pat) - start
	n := N / loop
	ret += n * tot
	rest := N % loop
	for i := 0; i < rest; i++ {
		ret += c.pat[start+i]
	}
	return ret, true
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 1000000)

	N, X, M := getInt(), getInt(), getInt()

	c := newCounter(N, M)
	for {
		sum, flg := c.append(X, N)
		// out(sum, flg, X, N)
		if flg {
			out(sum)
			return
		}
		X *= X
		X %= M
	}

}