object Main {
  import scala.io.StdIn._
  import scala.annotation.tailrec
  def main(args: Array[String]): Unit = {
    val Array(n, k, _*) = readLine().split(' ').map(_.toLong)
    def calc(x: Long, k: Long) = Math.abs(x - k)
    @tailrec
    def loop(x: Long, min: Long, history: Set[Long]): Long =
      if (min == 0L) 0L
      else if (history.contains(x)) min
      else {
        val newX = if (x > k) x % k else k - x
        val newMin = Math.min(newX, min)
        loop(newX, newMin, history + x)
      }
    println(loop(n, Long.MaxValue, Set.empty))
  }
}