n, x, m = $stdin.readline.chomp.split.map(&:to_i)
r = Array.new(m, 0)

res = x - x % m
m.times do |i|
  if i == 0
    r[i] = x % m
    next
  else
    r[i] = (r[i - 1] ** 2) % m
  end

  if r[i] == 0
    n = i + 1
    break
  elsif r[i] == 1
    res += (n - i - 1)
    n = i + 1
    break
  end
end
puts res + (0...m).map {|x| (r[x] || 0) * ((n - x - 1 + m) / m) }.inject(:+)
