program sequence_sum
  implicit none
  integer(8) :: n, m, num, a(0:100000) = 0
  integer :: x, b(0:100000) = 0, period, offset, rem, i
  read(*,*) n, x, m
  if (n == 1) then
    write(*,'(i0)') x
    stop
  end if
  a(1) = x
  b(x) = 1
  do i = 2, int(m) + 1
    x = int(mod(int(x, 8) * x, m))
    a(i) = a(i - 1) + x
    if (i == n) then
      write(*,'(i0)') a(i)
      stop
    end if
    if (b(x) > 0) then
      offset = b(x) - 1
      period = i - offset - 1
      exit
    end if
    b(x) = i
  end do
  num = (n - offset) / period
  rem = int(n - offset - num * period)
  write(*,'(i0)') (a(offset + period) - a(offset)) * num + a(offset + rem)
end program sequence_sum