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())

if N%K == 0:
    print("0")
elif abs(N%K- K)<N:
    print(abs(N%K- K))
else:
     print(N)

Submission status: Accepted

Solution code:
# template by 3xC and starkizard.
# contributors: 

#####################################################################################
from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""


# from bisect import bisect_left, bisect_right, insort
# from heapq import heappop, heapify, heappush
# from random import randint as rn
# from Queue import Queue as Q
# from copy import deepcopy
# from decimal import *
# import re
# import operator

#####################################################################################
# this enables you to write python3 code with PyPy2 (Python 2)
if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

#####################################################################################

"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""
# import threading
# threading.stack_size(1<<27)
# sys.setrecursionlimit(10000

def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    # Comment code out when you don't need inverse factorial or vice versa
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t



def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): # math.gcd is slower
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True
def ceil(n, k=1): return n // k + (n % k != 0) #returns math.ceil but protecting against floating inconsistencies
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) #inputs integer
def mi(): return map(int, input().split()) # inputting space seperated variables for example x,y,z
def li(): return list(map(int, input().split())) #inputting a space seperated list of integers
def lw(): return input().split() #inputting a space seperated list of strings
def lcm(a, b): return abs(a * b) // gcd(a, b) #returns LCM of two arguments
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) #For printing an iterable with seperator sep as optional second argument (default : " "), ending character (default: "\n") as optional third
def dd(): return defaultdict(int) #returns a dictionary with values defaulted to 0
def ddl(): return defaultdict(list) #returns a dictionary with values defaulted to []
def write(s): return sys.stdout.write(s)












###################################################################
def main():
    #CODE GOES HERE:
    n,k=mi()
    n=n%k
    print(min(abs(n),abs(n-k)))




""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

""" main function"""

if __name__ == '__main__':
    main()
    # threading.Thread(target=main).start()

Submission status: Accepted

Solution code:
n, k = list(map(int, input().split()))
if n >= k:
  n = n % k
  if n >= k // 2 + 1:
    n = k - n
else:
  while(True):
    if n > abs(n-k):
      n = abs(n-k)
    else:
      break
print(n)

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    a = n % k
    b = abs(a - k)
    print(a) if a < b else print(b)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
N = N%K
history = []
min_num = 0
while True:
  if (N==0):
    min_num = N
    break
  elif N in history:
    min_num = min(history)
    break 
  history.append(N)
  N = abs(N-K)

print(min_num)

Submission status: Accepted

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

if N >= K :
    t = N%K
    ans = min(t,K-t)
else:
    ans = min(N,K-N)
    
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
a = []
t = N%K
tt = abs(t-K)
a.append(t)
a.append(tt)

print(min(a))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
n,k = map(int,input().split())
     
#m = math.floor(n/k)
n = n%k
     
print(min(n,k-n))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
## coding: UTF-8
from decimal import *
from itertools import permutations, combinations,combinations_with_replacement,product
s = input().split()
t = [int(p) for p in s]

N = t[0]
K = t[1]

#p = int(N/K)
#a = N - p * K
#a = Decimal(N % K)
#b = Decimal(K - a)
a = N % K
b = K - a

#print('N:{}, K:{}, p:{}, a:{}, b:{}'.format(N,K,p,a,b))
print(min(a,b))
# 1000000000000000000

Submission status: Accepted

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

print(min(ans1, ans2))

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

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

if n%k > k/2:
  print(k - n%k)
else:
  print(n%k)

Submission status: Accepted

Solution code:
import sys
n,k=map(int,input().split())
if n==0 or n%k==0:
    print(0)
    sys.exit()
n=n%k
tmp=abs(n-k)
while tmp<n:
    n=tmp
    tmp=abs(n-k)
print(n)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    N = N%K
    while True:
        N_ = abs(N-K)
        if N_ < N:
            N = N_
        else:
            break
    print(N)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
#     combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

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

def main():
    n,k = readInt()
    ans = n % k
    ans = min(ans,abs(ans-k))
    print(ans)
    return

if __name__=='__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
a = (N // K) + 1

ans1 = -(N-K*a)
ans2 = N - (K*(N//K))
print(min(ans1,ans2))

Submission status: Accepted

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

a = n%k

num = min(a, abs(a-k))

print(num)

Submission status: Accepted

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

if n >= k:
  n %= k

print (min(k-n,n))

Submission status: Accepted

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

ans1 = n%k
ans2 = k - n%k

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

Submission status: Accepted

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

Submission status: Accepted

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

a = n%k
b = abs(n%k - k)

print(min(a, b))

Submission status: Accepted

Solution code:
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    n,k=INTM()
    a=n%k
    b=k-a
    print(min(a,b))
    
if __name__ == '__main__':
    do()

Submission status: Accepted

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

a = n % k
b = abs(a-k)

print(min(a, b))

Submission status: Accepted

Solution code:
N,K  = (int(X) for X in input().split())
print(min(N%K,abs(N%K-K)))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#

import sys
input=sys.stdin.readline

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

Submission status: Accepted

Solution code:
#C
N,K = map(int,input().split())
times = N//K
newN = N - K*times
ans = abs(newN-K)
print(min(newN,ans))

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

D1 = N//K
D2 = N//K+1

Ans = min(abs(N-D1*K) ,abs(N-D2*K))
print(Ans)

Submission status: Accepted

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

D = N%K
print(min([abs(D-K), D]))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
if k>=n:
  print(min(k-n,n))
else:
  m=n-(n//k)*k
  print(min(k-m,m))

Submission status: Accepted

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

print(ans)

Submission status: Accepted

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

r = N%K
if r <= int(K/2):
    print(r)
else:
    print(abs(r-K))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	#a = int(input())
	n, k = tin()
	#s = input()
	ret = min(k, n % k, k-(n%k))
	print(ret)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

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

Submission status: Accepted

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

answer = N % K
x = K - answer

if answer > x:
    answer = x

print(answer)

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:
import sys
N,M=map(int,input().split())
if M==0:
  print(N)
  sys.exit()
c=N%M
d=abs(c-M)
print(min(c,d))

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())


if n % k > k/2:
    print(k-(n % k))
else:
    print(n % k)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

## Library

import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter

## input

# n=int(input())
# A,B,C,D=map(int, input().split())
# string = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]

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

## Logic

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split(' '))
if N%K == 0:
    print(0)
else:
    tmp = [abs(N - N//K*K)]
    while True:
        if abs(tmp[-1] - K) in tmp:
            break
        else:
            tmp.append(abs(tmp[-1] - K))
    print(min(tmp))

Submission status: Accepted

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


resolve()

Submission status: Accepted

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

def solve(N: int, K: int):
    N = Decimal(str(N))
    K = Decimal(str(K))
    print(abs(N - K*round(N/K)))


# Generated by 1.1.7.1 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=map(int,input().split())

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys


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

def main():
    n, k = map(int, input().split())
    a = n % k
    print(min(a, k-a))

main()

Submission status: Accepted

Solution code:
# Template 1.0
import sys, re
from decimal import *
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, floor, trunc
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n,k = MAP()

if(k>=n):
    if(k>2*n):
        ans = n
    else:
        ans = k-n
else:
    rem = n%k
    quot = n//k

    ans = n-quot*k

    ans = min(ans, abs(ans-k))

print(ans)

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

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

if n >= k:
    n = n % k
    
if abs(n-k)<n:
    n = abs(n-k)
    print(n)
else:
    print(n)

Submission status: Accepted

Solution code:
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush,heapify
import math
from copy import deepcopy
import queue
import numpy as np
# sympy as syp(素因数分解とか)
Mod = 1000000007
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[y] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)

def main():  #startline-------------------------------------------
    n, m = map(int, input().split())
    print(min(abs(n%m),abs(n%m-m)))
if __name__ == "__main__":
    main() #endline===============================================

Submission status: Accepted

Solution code:
N,K =list(map(int,input().split()))
if N < K:
    mod=N
else:
    mod=N%K

if abs(mod-K) < mod:
    ans=abs(mod-K)
else:
    ans=mod
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

if N % K == 0:
  print(0)
else:
  q = N // K
  d = N - K*q
  print(min(d,abs(d-K)))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
# 引き算だとタイムアウトになる。最小イコール余りになる。
# 絶対値だからプラマイ
print(min(n%k,-n%k))

Submission status: Accepted

Solution code:
# C - Replacing Integer
N,K = map(int,input().split())
print(min(N%K, K-N%K))

Submission status: Accepted

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

a = x % k
b = abs(a - k)

if a > b:
    print(b)
else:
    print(a)

Submission status: Accepted

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


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode('utf-8')


#import numpy as np

def main():
	n,k=MI()
	ans=n%k

	print(min(ans,k-ans))










if __name__ == "__main__":
	main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = list(map(int,input().split()))
M = N // K
ans = N - M * K
ans = min(ans, abs(ans - K))
print(ans)

Submission status: Accepted

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

if t < k - t:
    print(t)
else:
    print(k-t)

Submission status: Accepted

Solution code:
import numpy as np
n, k = map(int, input().split())
ans = n%k , (k-n%k)%k 
answer = np.min(ans)
print(answer)

Submission status: Accepted

Solution code:
import sys
n,k=map(int,input().split())
if n == 0:
  print(n)
  sys.exit()
if n > k:
  n = n % k
if 2*n>k:
  n = k-n
print(n)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
if k == 1:
    print(0)
    exit()
m = n // k
ans1 = n - k * m
ans2 = - (n - k * (m + 1))
print(min(ans1, ans2))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

div=int(N//K)
sub=N-K*div
if sub>abs(sub-K):
    min_val=abs(sub-K)
else:
    min_val=sub

print(min_val)

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

if N > K:
    N = N - (N // K) * K

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

Submission status: Accepted

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

ans=N%K
if ans<=K/2:
    print(ans)
else:
    print(abs(K-ans))

Submission status: Accepted

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

temp_c = N % K

if temp_c < K:
    ans = min([temp_c, abs(K-temp_c)])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
div1,mod1 = divmod(n,k)
mod2 = (div1+1)*k-n
print(min(mod1,mod2))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=set()
for i in range(1,100000):
    n=n%k
    a.add(n)
    n=abs(n-k)
a=list(a)   
a.sort()
print(a[0])

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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


def solve(N: int, K: int):
    t = N % K
    ans = min(t, K - t)
    print(ans)
    return


# Generated by 1.1.7.1 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=map(int,input().split())
if n>k:
    n=n%k
    
n2=k-n
print(min(n,n2))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
while True:
    if N%K==0:
        print(0)
        break
    elif N<K:
        if N<K/2:
            print(N)
            break
        else:
            print(K-N)
            break
    else:
        N=N%K

Submission status: Accepted

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

Submission status: Accepted

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

tmp = n % k
ans = min(tmp, k - tmp)

print(ans)

Submission status: Accepted

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

tmp = n % k
if n >= k:
    ans = min(tmp, k - tmp)
else:
    ans = min(n, k - n)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
x, k = [int(i) for i in input().split()]
ans = min(x%k, k - x%k)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[19]:


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


# In[20]:


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


# In[ ]:

Submission status: Accepted

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

mod = N % K

if abs(mod-K) < mod:
    print(abs(mod-K))
else:
    print(mod)

Submission status: Accepted

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

# print(abs(n - k * round(n / k)))
a = n % k
print(min(a, abs(a - k)))

Submission status: Accepted

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

div_result = N // K
div_remainder = N % K
abs_value = abs(div_remainder - K)

if div_remainder <= abs_value:
    if div_result == 0:
        print(N)
    else:
        print(div_remainder)
else:
    print(abs_value)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n, k = map(int, readline().split())
if n <= k:
    print(min(n, abs(n-k)))
else:
    print(min((n % k), abs((n % k)-k)))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

n %= k

if(n < k/2):
    print(n)
else:
    print(k-n)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def resolve():
    N,K = map(int,input().split())
    A = N % K
    if K == 1:
        print(0)
    else: 
        print(min(A,K-A))
resolve()

Submission status: Accepted

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

Submission status: Accepted

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:


def solve(N, K):
    if N > K:
        N = N % K
    print(min(N, abs(N - K)))


if __name__ == '__main__':
    N, K = map(int, input().split())
    solve(N ,K)

Submission status: Accepted

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