END { load __FILE__ unless $stdin.eof? }

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

def f(x, m)
  x * x % m
end

x1 = x2 = x
i = 0
begin
  i += 1
  x1 = f(x1, m)
  x2 = f(f(x2, m), m)
end while x1 != x2

x1 = x
j = 0
begin
  j += 1
  x1 = f(x1, m)
  x2 = f(x2, m)
end while x1 != x2

k = 0
begin
  k += 1
  x1 = f(x1, m)
  x2 = f(f(x2, m), m)
end while x1 != x2

if n <= j
  s = n.pred.times.sum(x) { x = f(x, m) }
  puts s
else
  s0 = j.pred.times.sum(x) { x = f(x, m) }

  n -= j
  s1 = k.times.sum { x = f(x, m) }
  s2 = (n % k).times.sum { x = f(x, m) }

  puts s0 + s1 * (n / k) + s2
end
