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)

#[allow(unused_imports)]
use proconio::{input, marker::*};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

fn main() {
    input! {
        n: usize,
        x: usize,
        m: usize,
    }
    let mut map = BTreeMap::new();
    let mut vec = vec![0; m];

    let mut a = x;
    vec[0] = x;
    map.insert(a, 0);
    let mut val = None;
    for i in 1..m + 1 {
        a = a * a % m;
        if let Some(&j) = map.get(&a) {
            val = Some((j, i));
            break;
        }
        vec[i] = a;
        map.insert(a, i);
    }

    let (l, r) = val.unwrap();
    let begin = vec.iter().take(l).sum::<usize>();
    let sum = vec.iter().skip(l).take(r - l).sum::<usize>();

    if n <= l {
        println!("{}", vec.iter().take(n).sum::<usize>());
    } else {
        let rem = n - l;
        println!(
            "{}",
            begin + sum * (rem / (r - l)) + vec.iter().skip(l).take(rem % (r - l)).sum::<usize>()
        );
    }
}