思路:c++
假設a <= b,lcm(a + k, b + k) = (a + k) * (b + k) / gcd(a + k, b + k) = (a + k) * (b + k) / gcd(b - a, a + k)(根據gcd(a, b) = gcd(b - a, a)),因此枚舉b - a的全部因子便可。spa
實現:code
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const ll INF = 0x3f3f3f3f3f3f3f3f; 5 ll cal(ll x, ll y, ll i, ll & minn, ll & ans) 6 { 7 if (i > x) 8 { 9 if (y + i - x < minn) 10 { 11 minn = y + i - x; 12 ans = i - x; 13 } 14 } 15 else 16 { 17 ll k = 0; 18 if (x % i) k = (x / i + 1) * i - x; 19 ll t = (x + k) * (y + k) / __gcd(y - x, x + k); 20 if (t < minn) 21 { 22 minn = t; 23 ans = k; 24 } 25 } 26 } 27 int main() 28 { 29 ll a, b; 30 while (cin >> a >> b) 31 { 32 ll x = min(a, b), y = max(a, b); 33 if (y % x == 0) { cout << 0 << endl; continue; } 34 ll minn = INF, ans = 0; 35 for (int i = 1; i * i <= y - x; i++) 36 { 37 if ((y - x) % i == 0) 38 { 39 cal(x, y, i, minn, ans); 40 if ((y - x) / i != i) cal(x, y, (y - x) / i, minn, ans); 41 } 42 } 43 cout << ans << endl; 44 } 45 return 0; 46 }