#include <bits/stdc++.h>
#define ll long long
#define INF 999999999
#define N (1<<17)
#define M 1000000007
using namespace std;
int gcd(int a, int b) {
if (!b) return a;
return gcd(b, a % b);
}
int main () {
int n, m;
cin>>n>>m;
n = n % m;
int ans = 0;
if (!n) cout<<0<<endl;
else if (n == m) cout<<0<<endl;
else if (n < m) {
int l = m;
ans += n * (l / n);
l %= n;
if (!l) ans -= n;
if (l) {
if (m % l) {
ans += l - 1;
}
}
}
ans2 = INF;
if (n < m) {
int ans2 = n * (m % n);
m -= m % n;
if (n == m) break;
else {
m /= n;
ans2 += n * m - n;
}
}
cout<<min(ans, ans2)<<endl;
}