n, x, m = gets.split.map(&:to_i)

opens = Hash.new()
accum = [0]
cnt = 0
a = x

while !opens.include?(x)
  accum << a
  opens[x] = cnt
  x = (x * x) % m
  a += x
  cnt += 1
end

pathlen = opens[x]
pathaccum = accum[pathlen]
loopsize = cnt - pathlen
loopaccum = accum[cnt] - accum[pathlen]
loopstart = x


res = 0
if n <= pathlen
  res = accum[n]
else
  t = (n - pathlen) / loopsize
  rest = n - pathlen - t * loopsize

  a = pathaccum + loopaccum * t
  x = loopstart
  rest.times do |i|
    a += x
    x = x * x % m
  end

  res = a
end

p a
