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


r = x
res = x
r_set = Set.new
r_set << x
r_arr = [r]
ind = 0
(n-1).times do |i|
  ind = i
  r = r ** 2 % m
  res += r
  break if r_set.include?(r)
  r_set << r
  r_arr << r
end

count = 0
sum = 0
r_arr.reverse.each do |rnum|
  count += 1
  sum += rnum
  break if r == rnum
end
res += ((n - r_arr.length) / count) * sum

de = (n - r_arr.length) % count
(de - 1).times do 
  r = r ** 2 % m
  res += r
end
puts res
