n, x, m = gets.split(" ").map &:to_i
a = []
i = 0
flg = true
aa = 0
bb = 0
while flg
  if a.include?(x)
    aa = i
    bb = x
    flg = false
  else
    a.push(x)
  end
  x = (x%m)**2
  x %= m
  i += 1
  if i > n # || i >= Math.sqrt(m) 鳩ノ巣法
    flg = false
  end
end
if aa == 0
  puts a[0..n-1].sum
  exit
end
if n < aa
  puts a[0..n].sum
  exit
end
f = a.find_index(bb)
Q1 = a[0..f-1].sum
nn = n - f
Q2 = nn/(aa - f) * a[f..aa].sum
Q3 = a[f..(f+n%aa)].sum

#p Q1, Q2, Q3
p Q1 + Q2 + Q3