require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
n,x,m = gets.chomp.split.map(&:to_i)

loop_check = Array.new(m, false)

val = x
count = 0
sum = 0
val2count = Hash.new
a = []
cusum = []
until loop_check[val]
  loop_check[val] = true
  sum += val
  val2count[val] = count
  a[count] = val
  cusum[count] = sum
  count += 1

  if count == n
    puts sum
    exit
  end

  val = (val**2) % m
end
# p loop_check.map{|l| l ? 1 : 0}.join()

# p [count, sum, hash[val]]

count_at_loop = val2count[val]
if count_at_loop == 0
  first_sum = 0
else
  first_sum = cusum[count_at_loop - 1]
end

loop_sum = sum - first_sum
first_count = count_at_loop
loop_count = count - first_count
# p ['first_sum, loop_sum', first_sum, loop_sum]
# p ['first_count, loop_count', first_count, loop_count]
# p cusum

ans = first_sum
n -= first_count
# p [ans, n]

ans += (n / loop_count) * loop_sum
n = n % loop_count

# p [ans, n]
if n > 0
  loop_cusum = cusum[first_count..]
  # p loop_cusum
  ans += loop_cusum[n-1] - first_sum
end
puts ans
