n, x, m = gets.split.map(&:to_i)
a = Array.new(m, nil)
flag = Array.new(m, false)
accum = Array.new(m, 0)
prev = 0
j = n
for i in 0...m do
  a[i] = x
  accum[i] = prev + x
  prev = accum[i]
#  puts "#{a[i]} #{accum[i]}"
  flag[x] = true
  y = x ** 2 % m
  if flag[y]
    j = a.index(y)
#    puts "! #{j}"
    break
  end
  x = y
end
pre_len = j
loop_len = i - j + 1
post_len = ((n - j) % loop_len)
ans = accum[j - 1]
ans += (accum[i] - accum[j - 1]) * ((n - j) / loop_len)
ans += (accum[j + post_len - 1] - accum[j - 1])
puts ans
