let rec check n k =
  if n <= k && n <= abs (n - k) then n
  else if n <= k && n > abs (n - k) then abs (n - k)
  else
    let md = n mod k in
    check md k

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun a b -> (a, b)) in
  print_int @@ check n k