fun main(args: Array<String>) {
    val input = readLine()!!.split(" ").map { it.toLong() }
    println(getRes(input[0], input[1]))
}

fun getRes(n: Long, k: Long): Long {
    val x = if (n > k) n%k else k-n
    return if (n <= x) n else getRes(x, k)
}