line = gets.split(' ').map(&:to_i)

N = line[0]
X = line[1]
M = line[2]
Inf = 10**10

seq = [X]
for i in 2..M * 2 do
  seq[i-1] = (seq[i-2] ** 2) % M
end

res_deja = []
for i in 1..M do
  res_deja[i-1] = false
end

for i in 1..2*M do
  num = seq[i-1]
  if num >= M then
  elsif res_deja[num-1] then
    rep_end_id = i-2     #it must've ended in the previous time.
    rep_end_num = seq[i-1]
    break
  else
    res_deja[num-1] = true
  end
end
    
for i in 1..2*M do
  if seq[i-1] == rep_end_num then
    rep_start_id = i-1
    break
  end
end
  
rep_int = rep_end_id - rep_start_id + 1

loop_sum = 0
for i in rep_start_id..rep_end_id do
  loop_sum += seq[i]
end

if N - rep_start_id + 1 >= 0 then
  num_loop = (N - rep_start_id + 1) / rep_int
else
  num_loop = 0
end
before_loop_id = rep_start_id - 1
after_loop_id = rep_start_id + num_loop * rep_int
  
before_loop_sum = 0
for i in 0..before_loop_id do
  before_loop_sum += seq[i]
end

after_loop_sum = 0
for i in rep_start_id..(rep_start_id + (N - after_loop_id - 1)) do
  after_loop_sum += seq[i]
end

if X == 0 then
  puts 0
else
  puts before_loop_sum + loop_sum * num_loop + after_loop_sum
end