function Main(input) {
	const list = input.split(" ");
	const parse = a => parseInt(a.trim(), 10);
	const N = parse(list[0]);
	const X = parse(list[1]);
	const M = parse(list[2]);
	const rf = x => (x * x) % M;
	let tmp = rf(X);
	let ans = X;
	for(let i = 1;i < N; i++){
      	ans += tmp;
		tmp = rf(tmp);
	}
	console.log(ans);
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
