N, X, M = gets.split.map(&:to_i)
as = Array.new(M, nil)

c = X
m = 0
i = 0
g = false
while true do
  i += 1
  m += c
  if i == N then
    g = true
    puts m
    break
  end
  if as[c] == nil then
    as[c] = [i, m]
  else
    aa = as[c]
    ro = i - aa[0]
    rb = m - aa[1]
    loc = (N - i) / ro
    # pp [aa, i, m]
    i += loc * ro
    m += loc * rb
    break
  end
  c = c * c % M
end

if !g && i == N then
  puts m
  g = true
end

if !g then
  while true do
    # puts i
    c = c * c % M
    i += 1
    m += c
    if i == N then
      puts m
      break
    end
  end
end
