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

r = x
res = x
r_arr = [r]
r_hash = {r => 0}

(n-1).times do |i|
  r = r ** 2 % m
  break unless r_hash[r].nil?

  res += r
  r_arr << r
  r_hash[r] = i + 1
end

ind = r_hash[r]
sub_arr = r_arr[ind..-1]
sum = sub_arr.sum
count = sub_arr.length
res += ((n - r_arr.length) / count) * sum

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