#!/bin/bash

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