PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: alpha_ashwin
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
Chef has A marbles, and his friend has B.
What’s the minimum number of marbles that need to be transferred from one person to another, so that Chef’s marble count is divisible by his friend’s marble count?
Both people must have at least one marble.
EXPLANATION:
Suppose some marbles are transferred one way or another, and Chef ends up with X marbles.
The total number of marbles is A+B, so his friend must have A+B-X marbles.
This is a “good” final state if and only if X is a multiple of A+B-X.
Further, it’s easy to see that exactly |A-X| marbles need to be transferred to achieve this state:
- If X\geq A, Chef’s friend gives X-A marbles to him.
- If X\lt A, Chef gives A-X marbles to his friend.
Now, notice that X can only be between 1 and A+B-1, since there are A+B marbles in total, and both Chef and his friend should have at least one each.
So, loop over all such values of X, compute A+B-X, and check if it divides X.
If it does, you need |A-X| marbles to be transferred.
The final answer is the minimum among all these |A-X| values.
TIME COMPLEXITY:
\mathcal{O}(A+B) per testcase.
CODE:
Editorialist's code (Python)
for _ in range(int(input())):
a, b = map(int, input().split())
ans = 1000
for x in range(1, a+b):
y = a+b-x
if x%y == 0: ans = min(ans, abs(a-x))
print(ans)