local n, x, m = io.read("*n", "*n", "*n")
local t = {x}
local used = {}
used[x] = 1
local loopStartPos = false
local loopLength = -1
local prv = x
for i = 2, n do
  local nxt = (prv * prv) % m
  if used[nxt] then
    loopStartPos = used[nxt]
    loopLength = i - used[nxt]
    break
  end
  used[nxt] = i
  table.insert(t, nxt)
  prv = nxt
end
if n == #t then
  local sum = 0
  for i = 1, #t do
    sum = sum + t[i]
  end
  print(sum)
else
  local sum = 0
  for i = 1, loopStartPos - 1 do
    sum = sum + t[i]
  end
  local rem = n - (loopStartPos - 1)
  local loopCount = rem // loopLength
  local lpv = 0
  for i = loopStartPos, loopStartPos + loopLength - 1 do
    lpv = lpv + t[i]
  end
  sum = sum + lpv * loopCount
  local offset = loopStartPos - 1 + loopCount * loopLength
  for i = offset + 1, n do
    local pos = (loopStartPos - 1) + i - offset
    sum = sum + t[pos]
  end
  print(sum)
end
