# frozen_string_literal: true

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

a = x

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

b1, b2 = b.slice_before(l).to_a
b1 = [] if b1.nil?
b2 = [] if b2.nil?
remain = n - b.size
d = 0
dd = 0
if remain.positive?
  if b2.empty?
    b2 = [b1[0]]
    d = remain - 1
  else
    d = remain / b2.size
    dd = remain % b2.size
  end
end

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