Problem:


Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0



Sample input:
7 4


Sample output:
1

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
N = N % K if N >= K else N
print(min(N, abs(N-K)))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
if n%k==0:
  print(0)
#elif n<k:
#  print(n)
else:
  a=n//k
  q=n-a*k
  w=k-q
  s=min(w,q)
  print(s)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())

a = N//K

print(min(abs(N-K*a), abs(N-K*(a+1))))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
num=n//k
num*=k
num=n-num
print(min(num,abs(num-k)))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
if n%k == 0:
    print(0)
else:
    a = n//k
    b = n - (k*a)
    c = abs(n-(k*(a+1)))
    if b == c:
        print(b)
    else:
        print(min(b,c))

Submission status: Accepted

Solution code:
import sys
from math import ceil
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
 
# for i in range(int(ri())):
n,k = RI()
if k >= n:
    print(min(n,abs(k-n)))
else:
    temp= n%k
    print(min(temp,abs(k-temp)))

Submission status: Accepted

Solution code:
import sys
import heapq
from operator import itemgetter
 
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N,K = IL()
p = N - N//K*K

print(min(p, abs(K-p)))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
ans = min(abs(n-((n//k)*k)-k), abs(n-((n//k)*k)))
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())

n = N%K

print(min(abs(n-K), n))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
print(min((n-k)%k,k-((n-k)%k)))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
r = N % K
print(min(abs(K-r), r))

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    ans = min(n % k, abs(n % k - k))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def solve(N: int, K: int):

    n = N // K
    print(min(abs(n*K-N), abs((n+1)*K-N)))

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    solve(N, K)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
InputIntList = lambda : list(map(int, input().split()))
InputStrList = lambda : list(input().split())


def main():
    N, K = InputIntList()

    N = N % K

    if N == 0:
        print(0)
    else:
        print(min(N, abs(N - K)))

main()

Submission status: Accepted

Solution code:
n,k=list(map(int, input().split()))

a = n - (n//k)*k
b = abs(a - k)

print(min(a,b))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    n, k = [int(s) for s in input().strip().split()]
    n %= k
    result = min(n, k - n)
    print(result)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)


if __name__ == "__main__":
    N, K = tuple(map(int, input().split(" ")))
    M = N % K
    print(min(abs(K - M), M))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
n %= m
print(min(n, abs(n-m)))

Submission status: Accepted

Solution code:
def c_replacing_integer():
    N, K = [int(i) for i in input().split()]

    n = N % K
    return min(n, abs(n - K))

print(c_replacing_integer())

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

pos = n % k

neg = pos - k

print(min(pos, abs(neg)))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
if N <= K:
    print(min(K-N,N))
else:
    d = N%K
    print(min(K-d,d))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
temp = N // K
ans1 = N - K * temp
ans2 = abs(N - K * (temp + 1))

if ans1 < ans2:
    print(ans1)
else:
    print(ans2)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)

def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
# 入力全てを整数に変換したものの配列を受け取る
def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]

n,k = MI()
print((min(n%k, abs(n%k-k))))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

print(min(abs(n % k), abs((n % k) - k)))

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split(' ')))

a = N // K
b = N // K + 1

A = abs(N - K * a)
B = abs(N - K * b)

if A < B:
  print(A)
else:
  print(B)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())

a=N%K

print(min(a,K-a))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
if k == 1:
    print(0)
else:
    print(min(abs((n%k)-k),n%k))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

print(min(n%k,-n%k))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())

mod = N % K

mod_minus = mod - K

ans = min(mod, abs(mod_minus))

print(ans)

Submission status: Accepted

Solution code:
def main():
    x, K = list(map(int, input().split()))
    t = x // K

    return min(x, abs(K * t - x), abs(K * (t + 1) - x))

print(main())

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
if n > k:
    n = n % k
print(min(abs(k-n), n))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())

mod_x = n%k

print(min(mod_x, abs(mod_x-k)))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())

if K>N:
    print(min(N,K-N))
elif K==N:
    print(0)
else:
    print(min(N%K,abs(N%K-K)))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	n,k = MI()
	tmp = 0
	n = n%k
	while True:
		tmp = n
		n = min(n, abs(n-k))
		if(tmp == n):
			break
	print(tmp)


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
kouho1 = n//k
kouho2 = n//k + 1
print(min(abs(k*kouho1-n), abs(k*kouho2-n)))

Submission status: Accepted

Solution code:
n,k = list(map(int, input().split()))

print(min(n % k, -n % k))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
import sys
import math
import string
import collections
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

N, K = map(int, input().split())

print(min(N % K, K - (N % K)))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
print(min(n%k,abs(n%k-k)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    N,K=map(int,input().split())
    print(min(abs(N//K*K-N),abs((N//K+1)*K-N)))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())

x1 = N % K
x2 = K - x1

if x1 < x2:
	print(x1)
else:
	print(x2)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
if n <= k:
    print(min(n, abs(n - k)))
else:
    x = n % k
    print(min(x, abs(k - x)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n, k = [int(x) for x in input().split()]

a = n
b = k

if a > b:

    a -= (a // b) * b

    print(min(a, abs(a - b)))

else:
    print(min(a, abs(a - b)))

Submission status: Accepted

Solution code:
[N,K] = list(map(int,input().split()))

if N%K==0:
    out=0

else:
    amari=N%K
    out = min(amari, abs(amari-K))

print(out)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
t = N%K
print(min(t,abs(t-K)))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
ans=N%K
ans2=K-ans
ans3=min(ans,ans2)
print(ans3)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
n%=k
m=k-n
print(min(m,n))

Submission status: Accepted

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy, copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


def LIST(): return list(map(int, input().split()))


sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    n, k = MAP()
    print(min(n % k, k - n % k))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,K = map(int,input().split())

div = N % K
ans = min(div,abs(div-K))

print(ans)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

def main():
    n,k = inpm()
    if n == k or n%k == 0:
        print(0)
        return
    n = n%k
    print(min(n,abs(n-k)))
    
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split()))
print(min(abs(K-N%K), abs(N%K), N%K))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())

k2 = n % k

print(min(k2, k - k2))

Submission status: Accepted

Solution code:
N,K = [int(i.strip()) for i in input().split(' ')]

M = N % K
result = M if K -M > M else K-M
print(result)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()

def main():
    N, K = map(int, input().split())

    if N % K == 0:
        print(0)
    else:
        i = N // K
        print(min(abs(N - i * K), abs(N - (i+1) * K)))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
mod = 10**9+7
import sys
from collections import Counter, defaultdict, deque
from itertools import product, permutations, combinations
from itertools import accumulate
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from math import ceil,floor
from copy import deepcopy
from heapq import heappop,heappush,heapify
import heapq


sys.setrecursionlimit(10 ** 6)

int1 = lambda x: int(x) - 1

# リストの要素を改行を挟んで表示する
p2D = lambda x: print(*x, sep="\n")
# 入力を整数に変換して受け取る
def II(): return int(sys.stdin.readline())

def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())

# 入力全てを整数に変換したものの配列を受け取る
# def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]


def LI(): return list(map(lambda x:int(x), sys.stdin.readline().split()))
def HI(): return list(map(lambda x:int(x)*(-1), sys.stdin.readline().split()))


N,K = MI()
a = N%K
print(min(a,K-a))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())

x = N % K

ans = min(x,K-x)

print(ans)

Submission status: Accepted

Solution code:
#C - Replacing Integer
N,K= map(int, input().split())
a = N % K
if a <= abs(a-K):
    print(a)
else:
    print(abs(a-K))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())

if n>k:
    n-=n//k*k


print(min(k-n,n))

Submission status: Accepted

Solution code:
def get_ints():
    return map(int, input().split())

n, k = get_ints()

n %= k
print(min(n, k - n))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

n = n % k
print(min(n, k - n))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())

print(min(N%K,K-N%K))

Submission status: Accepted

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    m1=n%k
    m2=k-m1
    print(min(m1,m2))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, K = list(map(int, sys.stdin.buffer.readline().split()))


def solve(n, k):
    n = n % k
    return min(n, k - n)
ans = solve(N, K)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
if(N>=K):
    N = N%K
while(1):
    new_N = abs(N-K)
    if(new_N<N):
        N = new_N
    else:
        break
print(N)

Submission status: Accepted

Solution code:

def resolve():
    N,K = map(int,input().split())
    a = N % K

    print(min(a,K-a))




if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
N,K = map(int,input().split())

if N < K and abs(N-K) > N:
  print(N)
else:
  n = N % K
  print(min(n,abs(n-K)))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
new_x = n-k*(n//k)
print(min(abs(new_x-k),new_x))

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#def print(x): return sys.stdout.write(str(x)+'\n')
#sys.setrecursionlimit(100000)
mod=int(1e9+7)

n,k=mdata()
n=n%k
print(min(n,k-n))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
print(min(n % k, abs(n % k - k)))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())

if N >= K:
    N = N%K

print(min(N,K-N))

Submission status: Accepted

Solution code:
import math
from collections import defaultdict
ml=lambda:map(int,input().split())
ll=lambda:list(map(int,input().split()))
ii=lambda:int(input())
ip=lambda:input()

"""========main code==============="""

x,y=ml()
a=x%y
print(min(a,y-a))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

ans = n%k

while True:
    if ans > abs(ans-k):
        ans = abs(ans -k)
    else:
        break

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, k = map(int, input().split())
print(min(n, n-n//k*k, (n+k-1)//k*k-n))

Submission status: Accepted

Solution code:
# coding: utf-8

N,K=map(int,input().split())

print(min(N%K,K-N%K))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
rem = n%k
print(min(rem, k-rem))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())

N = N % K
print(min(N, abs(N - K), abs(abs(N - K) - K)))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
t = n % k
res = min(t, abs(t - k))
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int):
    print(min(N % K, abs(N % K - K)))
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    solve(N, K)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = [int(i) for i in input().split()]
N = N%K + K
a = abs(N-K)
cand = [a, K-a]
print(min(cand))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
if n<=k:
  ans = min(abs(n-k),n)
else:
  a = n-(n//k)*k
  ans = min(a,abs(a-k))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
m = n % k
print(min(m, k - m))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n,k=mii()

a=n%k
b=abs(a-k)
print(min(a,b))

Submission status: Accepted

Solution code:
a,b=[int(i) for i in input().split()]
p=a//b
print(min(abs(a-p*b-b),a-p*b))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
ans = n%k
print(min(ans,-ans%k))

Submission status: Accepted

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k=map(int, readline().rstrip().split())

    x=n%k
    y=abs(x-k)
    print(min(x,y))
    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Accepted

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,k = mi()
if n == 0:
    print(0)
    exit()
ans = n
temp1 = n % k
temp2 = k - temp1
ans = min(temp1,ans)
ans = min(temp2,ans)
print(ans)

Submission status: Accepted

Solution code:
def main():
    N,K = map(int,input().split())
    a = (N % K)
    b = abs(a - K)
    print(min(a,b))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!python3

# input
N, K = list(map(int, input().split()))


def main():
    s = N % K
    ans = min(s, K - s)
    print(ans)    


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, k = tuple(map(int, input().split()))

ans1 = n % k
ans2 = abs(n % k - k)
print(min(ans1, ans2))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
if n > k:
    n = n % k
print(min(n, k - n))

Submission status: Accepted

Solution code:
n, k = map(int, input().strip().split())

ans=n%k
ans=min(ans,abs(ans-k))
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
l = n//k
print(min(n-k*l, abs(n-k*(l+1))))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
mod = n % k
if abs(mod) > abs(mod-k):
    print(abs(mod-k))
else:
    print(mod)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
n=n%k
print(min(n,abs(k-n)))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=n//k
print(min(n-k*a, k*(a+1)-n))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
n=n%k
print(min(n,abs(n-k)))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
if n>k:
    n=n-n//k*k
ans=10**18+10
for i in range(10000):
    ans=min(ans,n)
    n=abs(n-k)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
m = n % k
print(min(m, abs(k-m)))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
s=n//k
a=n-s*k
aa=abs(a-k)
bb=abs(aa-k)
print(min(aa,bb))

Submission status: Accepted

Solution code:
n,k = list(map(int,input().split()))
print(min(abs(n-((n//k)+1)*k), n-(n//k)*k))

Submission status: Accepted

Solution code:
def main():

    N, K = map(int, input().split())
    return min([N, N%K, K-N%K])

if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
n, k = map(int, input().split())

h = n%k

if h >= k/2:
    print(abs(h-k))
else:
    print(h)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int):
    n = N % K
    for _ in range(100):
        n = min(n, abs(n - K))
    print(n)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    solve(N, K)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from sys import stdin
import sys
sys.setrecursionlimit(10**8)

def nextLine(): return next(stdin)
def nextStrList(): return nextLine().split()
def nextIntList(): return [int(_) for _ in nextStrList()]


def main():
	n,k=nextIntList()
	x=n%k
	x1=abs(x-k)
	print(min(x,x1))

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
print(min(n, abs(n-(n//k)*k), abs(n-(n//k+1)*k)))

Submission status: Accepted

Solution code:
N, K = [int(i) for i in input().split()]
n = N % K 
print(min(n, K - n))

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from string import ascii_uppercase
import sys, bisect, math, heapq

stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

N, K = read_int()

def solve():
    ans = N % K
    return min(ans, abs(ans - K))

if __name__ == "__main__":
    print(solve())

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq


def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def main():
    N, K = iip(True)
    N = N % K
    N = min(N, (K-N))
    print(N)


def solve():
    N = iip(False)
    S = input()


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_=mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7



n, k = LI()
print(min(n % k, k - n % k))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
a=N//K
print(min(N-a*K,abs(N-(a+1)*K)))