n,x,m = gets.strip.split.map(&:to_i)
v = Array.new(m,0)
c = Array.new(m,0)
a = Array.new(m,0)
ans = 0
n.times do |i|
  break if x == 0
  ans += x
  y = x * x % m
  if v[x] == 0
    v[x] = y
    c[x] = i
    a[x] = ans
  else
    l = ans - a[x]
    s = i - c[x]
    z = (n - i - 1)/s
    ans += z * l
    (i+z*s+1).upto(n-1) do
      ans += y
      y = v[y]
    end
    p ans
    exit
  end
  x = y
end
p ans
