N,X,M = gets.split.map &:to_i
A = [p]*M
I = [p]*M
H = {0=>0,X=>1}
S = [0,s=X]
A[0] = I[0] = 0
I[X] = n=1
A[1] = x=X
while M > n+=1
  M>x*=x or x%=M
  break  if I[x]
  I[x] = n
  A[n] = x
  S[n] = s+=x
end
exit 0&p(S[N]) if S[N]
exit 0&p(s) if x==0
i = I[x]
L = A[i...n]
T = S[i...n]
d = T[0] - L[0]
q,r = (N-i).divmod L.size
p q*(s-d) + T[r]