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

Solution in Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)



import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {

	public static void main(String args[]) throws Exception {
		MyScanner sc = new MyScanner();
		out = new PrintWriter(new BufferedOutputStream(System.out));
		
		long n = sc.nextLong();
		long k = sc.nextLong();
		long min = n;
		if(k == 1) {
			System.out.println("0");
			return;
		}
		if(n % k == 0) {
			System.out.println("0");
			return;
		}
		if(n > k) {
			long divisor = n / k;
			long rem = n - (divisor * k);
			n = rem;
		}
		min = n;
		while(Math.abs(n - k) <= min) {
			n = Math.abs(n - k);
			min = Math.min(min, n);
		}
		System.out.println(n);
	}

	public static PrintWriter out;

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

	}

}