n,x,m = gets.chomp.split(" ").map(&:to_i)
hash = Hash.new(0)
cnt = 0
ans = 0
loopans = 0
loopcnt = 0
y = x
while (hash[y] == 0 || hash[y] == 1) && cnt <= n-1
  hash[y] += 1
  ans += y
  loopans += y if hash[y] == 2
  loopcnt += 1 if hash[y] == 2
  cnt += 1
  y = (y*y) % m
end
if cnt >= n
  puts ans
else
  ans += loopans * ((n-cnt) / loopcnt)
  rest = (n-cnt) % loopcnt
  rest.times do
    ans += y
    y = (y*y) % m
  end
  puts ans
end
