n, x, m = gets.split(' ').map(&:to_i)
a = x
seen = {}
sum = 0

i = 0
start = nil
nums = []
while i < n
  nums << a
  if seen[a]
    start = seen[a]
    break
  end
  sum += a
  seen[a] = i
  i += 1
  a = (a * a) % m
end
if i == n {
  puts sum
  exit
}
len = i - start

rangesum = 0
(start...i).each do |j|
  rangesum += nums[j]
end

slots = (n - i) / len
r = (n - i) % len
total = sum + rangesum * slots
r.times do
  total += a
  a = (a * a) % m
end

puts total
