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

a = Array.new(m)
index = Array.new(m,-1)

a[0] = x
index[x] = 0

sum = x

for i in 1...n
  t = (a[i-1] * a[i-1]) % m
  if index[t] == -1
    a[i] = t
    sum += t
    index[t] = i
  else
    loop_start = index[t]
    loop_end = i-1
    loop_sum = 0
    for j in loop_start..loop_end
      loop_sum += a[j]
      if j - loop_start + 1 == (n-i) % (loop_end-loop_start+1)
        sum += loop_sum
      end
    end
    sum += loop_sum * ((n-i) / (loop_end-loop_start+1))
    break
  end
end

puts sum 