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