We know that:
a + x is divisible by ;
b + x is divisible by ;
Therefore, a + b + x is divisible by both and , which is equivalent to its divisibility by LCM(a, b). That is, there exists an integer such that:
We take x = LCM(a, b) - a - b as the solution. However, if this value is negative, we instead use:
It is evident that a + b \le 2 \cdot LCM(a, b).
Example
In the second example a = 3, b = 4.~LCM(3, 4) = 12.
The answer is x = LCM(a, b) - a - b = 12 - 3 - 4 = 5.
In the third example a = 123, b = 123. LCM(123, 123) = 123.
The answer is x = LCM(a, b) - a - b = 123 - 123 - 123 = -123. Since this value is negative, the answer is
Algorithm implementation
The function gcd computes the greatest common divisor of the numbers and .
long long gcd(long long a, long long b)
{
return (!b) ? a : gcd(b, a % b);
}Read the input data.
cin >> a >> b;Compute lcm = LCM(a, b) = (a \cdot b)~/~GCD(a, b).
lcm = a / gcd(a, b) * b;Compute the answer.
res = lcm - a - b;
if (res < 0) res += lcm;Print the answer.
cout << res << endl;