#!/bin/bash

awk -M '\
function abs(x){
    x+=0;
    return x > 0 ? x : -x
}
{
    N=$1; K=$2;
    N -= int(N/K)*K
    b = N
    while(1){
        N=abs(N-K);
        if(b<N)break
        b = N
    }
    print b
}' 
