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 Rust (1.42.0) (judge verdict: Accepted)

fn solve() {
    let (n, x, m): (usize, usize, usize) = (read::<usize>(), read::<usize>(), read::<usize>());
    let mut v = vec![];
    let mut k = HashSet::new();
    let mut base = x;
    let mut res: usize = 0;
    // 周期後
    let mut cyc = vec![];
    let mut rem: usize = 0;
    for i in 0..n {
        // 周期発見
        // 周期の長さを取る
        if k.contains(&base) {
            // 残り回数は, n-i
            rem = n - i;
            while let Some(u) = v.pop() {
                if u == base {
                    cyc.push(base);
                    cyc.reverse();
                    break;
                }
                cyc.push(u);
            }
            break;
        }
        k.insert(base);
        // println!("{}", base % m);
        v.push(base);
        res += base;
        base *= base;
        base %= m;
    }
    if rem != 0 {
        // 商だけ答えに和を足して,
        let (q, r) = (rem / cyc.len(), rem % cyc.len());
        res += q * cyc.iter().sum::<usize>();
        // あまりは調整
        for i in 0..r {
            res += cyc[i];
        }
    }
    println!("{:?}", res);
}

fn main() {
    let stack_size = 104_857_600;
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

// =========
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};
#[allow(unused_imports)]
use std::process::exit;

#[allow(dead_code)]
const MOD: usize = 998_244_353;

fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// =========