n, x, m = $stdin.readline.chomp.split.map(&:to_i)
dv = Array.new(m, 0)
used = Hash.new

res = 0
q = []
m.times do |i|
  if i == 0
    y = x
  else
    y = (dv[i - 1] ** 2) % m
  end

  if !used[y].nil?
    used[y].step(i - 1) do |j|
      q << dv[j]
    end
    n -= i
    break
  else
    dv[i] = y
    used[y] = i
    res += y
  end
end

q.size.times do |i|
  res += q[i] * ((n - i + q.size - 1) / q.size)
end
puts res