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)

use std::fmt::Debug;
use std::str::FromStr;

pub struct TokenReader {
    reader: std::io::Stdin,
    tokens: Vec<String>,
    index: usize,
}

impl TokenReader {
    pub fn new() -> Self {
        Self {
            reader: std::io::stdin(),
            tokens: Vec::new(),
            index: 0,
        }
    }

    pub fn next<T>(&mut self) -> T
    where
        T: FromStr,
        T::Err: Debug,
    {
        if self.index >= self.tokens.len() {
            self.load_next_line();
        }
        self.index += 1;
        self.tokens[self.index - 1].parse().unwrap()
    }

    pub fn vector<T>(&mut self) -> Vec<T>
    where
        T: FromStr,
        T::Err: Debug,
    {
        if self.index >= self.tokens.len() {
            self.load_next_line();
        }
        self.index = self.tokens.len();
        self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()
    }

    pub fn load_next_line(&mut self) {
        let mut line = String::new();
        self.reader.read_line(&mut line).unwrap();

        self.tokens = line
            .split_whitespace()
            .map(String::from)
            .collect();
        self.index = 0;
    }
}

fn solve(n: i64, x: i64, m: i64) -> i64 {
    let mut seq = vec![];
    let mut index = vec![None; 1e5 as usize + 10];
    let mut sum_at = vec![0; 1e5 as usize + 10];

    let mut num = x;
    let mut sum = 0;

    while index[num as usize].is_none() && seq.len() < n as usize {
        index[num as usize] = Some(seq.len());
        sum_at[num as usize] = sum;

        sum += num;
        seq.push(num);
        num = (num * num) % m;
    }

    if seq.len() == n as usize {
        return sum;
    }

    let left = n as usize - seq.len();
    let len = seq.len() - index[num as usize].unwrap();
    let chunk_sum = sum - sum_at[num as usize];

    let whole = left / len;
    sum += chunk_sum * whole as i64;

    let left = left % len;
    for _ in 0..left {
        sum += num;
        num = (num * num) % m;
    }

    sum
}

fn main() {
    let mut reader = TokenReader::new();
    let n = reader.next();
    let x = reader.next();
    let m = reader.next();

    let res = solve(n, x, m);
    println!("{}", res);
}