n, x, m = gets.split.map(&:to_i)
a = [x]
h = {}
h[x] = 0
t = 0
n.pred.times do |i|
  t = a[i] * a[i] % m
  break if h.key?(t)
  h[t] = 0
  a << t
end
b = a.dup
a = a[0...a.find_index{ _1 == t }]
b -= a
ans = a.sum
if b.size > 0
  ans += b.sum * ((n - a.size) / b.size)
  ans += b[0, (n - a.size) % b.size].sum
end
puts ans
