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
  break if r_set.include?(r)
  res += r
  r_set << r
  r_arr << r
end


if r == 1
  puts res + (n - ind - 1)
elsif r == 0
  puts res
else
  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
end
