# frozen_string_literal: true

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

a = x

h = Hash.new { false }
l = -1
ind = n
b = []
n.times do |i|
  if h[a]
    l = a
    ind = i
    break
  end
  h[a] = true
  b.push a
  a *= a
  a %= m
end

j = b.find_index(l)
unless j.nil?
  if j > 0
    b1 = b[0..(j - 1)]
  else
    b1 = [b[0]]
  end
  b2 = b[j..(-1)]
else
  b1 = b
  b2 = []
end
remain = n - ind
d = 0
dd = 0
if remain > 0
  d = remain / b2.size
  dd = remain % b2.size
end

# p [b1, b2, ind, l, remain]

sum1 = b1.sum
sum2 = b2.sum * (d + 1)
sum = sum1 + sum2 + b2.take(dd).sum
puts sum
