n, x, m = gets.split(' ').map{|i| i.to_i}
 
z = 0
a = Array.new
a[0] = x
k_s = nil
k_e = 0
z = x
(n - 1).times do |i|
  k_e = i
  a_last = a[-1] ** 2 % m
  k_s = a.index(a_last)
  if k_s
    break
  end
  a.push a_last
  z += a_last
end
  
if k_s
  roops = ((n - k_e) / (k_e - k_s + 1)) 
  roop_sum = a[k_s..-1].sum
  lest_sum = a[k_s..(k_s + (n - k_s ) % (k_e - k_s + 1) -1)].sum
  z = z + roop_sum * roops + lest_sum
end
  
puts z