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)

// This code is generated by [cargo-atcoder](https://github.com/tanakh/cargo-atcoder)
// Original source code:
/*
#![allow(unused_imports)]
use proconio::input;
use proconio::marker::*;
fn main() {
    input!(n: usize, x: u64, m: u64);
    let mut s = std::collections::BTreeSet::new();
    let mut arr = vec![0; (m+1) as usize];
    s.insert(x);
    arr[0] = x;
    let mut idx = 0;
    loop {
        let a = arr[idx];
        let v = (a * a) % m;
        arr[idx + 1] = v;
        if s.contains(&v) {
            break ;
        }
        s.insert(v);
        idx += 1;
    }
    // println!("s = {:?}, idx = {}", s, idx);
    let loop_end = idx + 1;
    let mut sum = 0;
    let mut loop_start = 0;
    while arr[loop_start] != arr[loop_end] {
        sum += arr[loop_start];
        loop_start += 1;
    }
    // println!("{} - {}", loop_start, loop_end);
    let loop_len = loop_end - loop_start;
    let rest = n - loop_start;
    let loop_cnt = rest / loop_len;
    let rest = rest % loop_len;
    let mut loop_sum = 0;
    for i in loop_start..loop_end {
        loop_sum += arr[i];
        if i < loop_start + rest {
            sum += arr[i];
        }
    }
    sum += loop_sum * (loop_cnt as u64);

    // println!("arr = {:?}", arr);
    // println!("loop [{}, {}] == len {} -> loop_cnt = {}\nrest = {}", loop_start,loop_end, loop_len, loop_cnt, rest);

    println!("{}", sum);
}
*/

fn main() {
    let exe = "/tmp/bin94F7F225";
    std::io::Write::write_all(&mut std::fs::File::create(exe).unwrap(), &decode(BIN)).unwrap();
    std::fs::set_permissions(exe, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    std::process::exit(std::process::Command::new(exe).status().unwrap().code().unwrap())
}

fn decode(v: &str) -> Vec<u8> {
    let mut ret = vec![];
    let mut buf = 0;
    let mut tbl = vec![64; 256];
    for i in 0..64 { tbl[TBL[i] as usize] = i as u8; }
    for (i, c) in v.bytes().filter_map(|c| { let c = tbl[c as usize]; if c < 64 { Some(c) } else { None } }).enumerate() {
        match i % 4 {
            0 => buf = c << 2,
            1 => { ret.push(buf | c >> 4); buf = c << 4; }
            2 => { ret.push(buf | c >> 2); buf = c << 6; }
            3 => ret.push(buf | c),
            _ => unreachable!(),
        }
    }
    ret
}

const TBL: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BIN: &'static str = "<base64-encoded ELF executable removed>";