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

a = [X]
mem = {}
ans = X
x = X
i = 1
while i < N
  x = (x**2) % M
  a << x
  if mem[x]
    j = mem[x][0]
    n = a[j...i].sum
    ans += n * ((N - i) / (i-j))
    ans += a[j,(N-i)%(i-j)].sum
    break
    i = N - (N - i) % i
  else
    mem[x] = [i, ans]
    ans += x
  end
  i += 1
end
puts ans