N,X,M = gets.split.map(&:to_i)

M2N = [nil]*M
N2M = []
a = X
until M2N[a]
	M2N[a] = N2M.size
	N2M << a
	a = a*a%M
end
C = M2N[a]

p N2M[0...[C,N].min].sum + [N-C,0].max/(N2M.size-C)*N2M[C,N2M.size].sum + N2M[C,[N-C,0].max%(N2M.size-C)].sum
