n,x,m = gets.split.map(&:to_i)
looop = [x]
forth = []
l = nil
k = nil
app = Hash.new(false)
app[x] = true
m.times do
  a = (looop[-1]**2)%m
  if a == 0
    puts looop.sum
    exit
  elsif app[a] == true
    z = looop.index(a)
    if z != 0
        forth = looop.slice(0..(z-1))
        k = firth.size
    else
        forth = [0]
        k = 0
    end
    if z == 0
        l = 1
    else
        looop.slice!(0..(z-1))
        l = looop.size
    end
    break
  else
    looop << a
    app[a] = true
  end
end
ans = forth.sum + ((n-k)/l)*looop.sum
if (n-k)%l==0
    puts ans
else
    puts ans+looop.slice(0..((n-k)%l-1)).sum
end
