#include<stdio.h>
#include<math.h>
int main() {
	long long n,k;
	while(~scanf("%lld %lld",&n,&k)) {
		if(k==1) {
			printf("0\n");
		} else {
			while(n>labs(n-k)) {
				n=labs(n-k);
			}
			printf("%lld\n",n);
		}
	}
	return 0;
}