n,x,m=gets.chomp.split(' ').map(&:to_i)
res = 0
buckets = Array.new(m, nil)
values = Array.new([m,n].min, 0)
buckets[x] = 0
values[0] = x
res += x
(1...n).each do |i|
  x = x * x % m
  values[i] = x
  if buckets[x].nil?
    buckets[x] = i
    res += x
  else
    j = buckets[x]
    d = i - j
    rotc = (n - i) / d
    rotv = values[j...i].sum
    res += rotc * rotv
    remain = n - (i + rotc * d)
    res += values[j...j+remain].sum
    break
  end
end
p res