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
a = a[1...a.find_index{ _1 == t }]
a.each{ h.delete(_1) }
ans = a.sum 
ans += h.keys.sum * ((n - a.size) / h.size)
ans += h.sort_by{ |k, v| v }.map{ |_1, _2| _1 }[0, (n - a.size) % h.size].sum
puts ans
