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 std::cmp::*;
use std::collections::*;
use std::io::Write;
use std::ops::Bound::*;

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

fn main() {
    let v = read_vec::<i64>();
    let (n, x, m) = (v[0], v[1], v[2]);
    let mut n = n - 1;
    let mut ans = x;
    let mut a = (x * x) % m;

    let mut found = HashSet::new();
    let mut roots = vec![];
    let mut cycle = 0;
    let mut cycle_begin = 0;
    for i in 0.. {
        found.insert(a);
        roots.push(a);
        // ans += a;
        a = (a * a) % m;
        if found.contains(&a) {
            for j in (0..roots.len()) {
                if roots[j] == a {
                    cycle = roots.len() - j;
                    cycle_begin = j;
                }
            }
            break;
        }
    }

    if n <= cycle_begin as i64 {
        ans += (0..n as usize).map(|x| roots[x]).sum::<i64>();
        println!("{}", ans);
        return;
    }
    ans += (0..cycle_begin).map(|x| roots[x]).sum::<i64>();
    n -= cycle_begin as i64;

    let roots = (cycle_begin..roots.len())
        .map(|x| roots[x])
        .collect::<Vec<_>>();

    let cycle_sum = roots.iter().sum::<i64>();
    ans += (n / cycle as i64) * cycle_sum;
    n %= cycle as i64;
    ans += (0..n).map(|x| roots[x as usize]).sum::<i64>();
    debug!(n, cycle_sum, cycle);
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}