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)

// e
fn main() {
    input! {
     n: usize,
     x: usize,
     m: usize,
    }
    let mut nexts = vec![0; m];
    for i in 1..m {
        let next = i * i % m;
        nexts[i] = next;
    }

    let mut visited = vec![false; m];
    let mut res = 0;
    res += x;
    visited[x] = true;
    for i in 2..n + 1 {
        x *= x;
        x %= m;
        res += x;
        if visited[x] {
            // 閉路に入った
            let start = x;
            let mut cum: Vec<usize> = Vec::new();
            cum.push(0);
            let mut length = 0;
            let mut current = start;
            while true {
                current = nexts[current];
                length += 1;
                cum.push(cum.last().unwrap() + current);
                if current == start {
                    break;
                }
            }
            // 残り何周できるか
            let j = (n - i) / length;
            res += cum[length] * j;
            // 1周未満で何回移動できるか
            let k = (n - i) - j * length;
            res += cum[k];
            break;
        } else {
            visited[x] = true;
        }
    }

    println!("{}", res);
}

#[macro_export(local_inner_maccros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}
#[macro_export(lcal_inner_macros)]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[macro_export(lcal_inner_macros)]
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}