n,x,m=gets.split.map(&:to_i)
ml=[0]*100001
l=[nil]
i=1
s,t=0,0
while i<=n
  if ml[x]>0
    s=ml[x]
    t=i-1
    break
  end
  ml[x]=i
  l << x
  i+=1
  x=x**2%m
end
if s==0
  puts l[1..n].sum
else
  c=l[1...s].sum
  c+=l[s..t].sum*((n-s+1)/(t-s+1))
  c+=l[s,((n-s+1) % (t-s+1))].sum
  puts c
end

