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

if x==0
  puts 0
  exit
end

sim = 0
i = 2
rec = []
rec[1] = x%m
while i < m+1 do
  if ((rec[i-1])**2)%m==0
    sim = 1
    break
  end
  unless rec.include?(((rec[i-1])**2)%m)
    rec[i] = ((rec[i-1])**2)%m
  else
    break
  end
  i += 1
end
rec.compact!
sum = rec.sum
if sim == 1
  puts sum
  exit
end
a = n/(i-1)
b = n%(i-1)
tum = 0
if b != 0
  for i in 0..b-1
    tum += rec[i]
  end
end

puts a*sum+tum