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

a = (0..(m + 1)).map { nil }
a[1] = x

h = { x => 1 }
b, d = nil, nil
(2..(m + 1)).each do |k|
  a[k] = (a[k - 1] * a[k - 1]) % m
  if h[a[k]]
    b = h[a[k]]
    d = k - b
    break
  end
  h[a[k]] = k
end

puts a[1, b].sum + a[b + 1, d].sum * ((n - b) / d) + a[b + 1, (n - b) % d].sum
