Gnome Paul is competing in the elimination round of the Gnome Math Cup. Problem F reads as follows.
You are given n positive integers a1,a2,…,an and a positive integer d. Find nonzero integers x1,x2,…,xn with ∣xi∣≤107 such that
a1x1+a2x2+⋯+anxn=d.
Gnomes dislike big numbers, so every ai and d is at most 106, and no xi may be 0.
Many sequences can satisfy the equation, so exactly one of them counts as the answer. Set sn+1=0 and, for i=n,n−1,…,1, set si=gcd(ai,si+1), so si is the greatest common divisor of ai,ai+1,…,an. A required sequence exists if and only if s1 divides d. When it exists, build it from left to right. Put D0=d, and for i=1,2,…,n−1 pick xi this way.
- xi is not 0, and Di=Di−1−aixi is not 0 and is a multiple of si+1.
- Among all such xi, take one that makes ∣Di∣ as small as possible.
- If two of them give the same ∣Di∣, take the smaller xi.
The last value is xn=Dn−1/an. For n=1 nothing is picked and x1=d/a1. Every value this rule produces satisfies ∣xi∣≤107.