n, x, m = gets.split.map(&:to_i)
a = []
a[1] = x
h = Hash.new(0)
h[x] = 1
t = 0
2.upto(n) do |i|
  t = a[i - 1] * a[i - 1] % m
  if h[t].zero?
    h[t] = i
    a[i] = t
  else
    break
  end
end
b = a.dup.compact
a = a[1...a.find_index{ _1 == t }]
b -= a
ans = a.sum
ans += b.sum * ((n - a.size) / b.size)
ans += b[0, (n - a.size) % b.size].sum
puts ans
