Long division returns the unique quotient and remainder full
This proof shows: correctness.
Let R be a commutative ring, f,g∈R[x], g=0, and let the leading coefficient of g be a unit. After line L1, f=∑i=0mfixi and g=∑j=0ngjxj with gn=0, and u=gn−1 after line L3. For a coefficient array r we write r also for the polynomial ∑irixi.
Case m<n. Line L2 returns (0,f). Then f=0⋅g+f and degf<n. This also covers f=0, where m=−1.
Case m≥n. We use this invariant of the loop of line L5. Before the step for k, with −1≤k≤m−n (the value k=−1 stands for the state after the last step):
(I1)f=Qkg+r,Qk=i=k+1∑m−nqixi,(I2)ri=0 for all i>n+k. Initialization. Before the step for k=m−n, line L4 gives r=f and Qm−n=0, so (I1) holds. (I2) says ri=0 for i>m, which is true because r=f has degree m.
Maintenance. Assume (I1) and (I2) before the step for k. Line L6 sets c=rn+ku, and line L7 sets qk=c, so Qk−1=Qk+cxk. Lines L8 and L9 replace rj+k by rj+k−cgj for 0≤j≤n−1. Line L10 replaces rn+k by 0. Since
rn+k−cgn=rn+k−rn+kugn=0, line L10 writes the value rn+k−cgn. So the step replaces rj+k by rj+k−cgj for each 0≤j≤n and does not change the other entries, that is, it replaces the polynomial r by r′=r−cxkg. Then
Qk−1g+r′=(Qk+cxk)g+r−cxkg=Qkg+r=f, which is (I1) for k−1. For (I2) at k−1 we need ri′=0 for i>n+k−1. For i>n+k, the step does not change ri, which is 0 by (I2). For i=n+k, line L10 sets rn+k′=0.
Termination. The loop runs exactly m−n+1 times. After the step for k=0, (I1) and (I2) with k=−1 give
f=qg+r,q=i=0∑m−nqixi,ri=0 for i≥n. So r=∑i=0n−1rixi, which line L11 returns, and degr<n=degg. Stripping zero top coefficients in line L11 does not change the polynomials q and r.
Uniqueness. If also f=q′g+r′ with degr′<n, then (q−q′)g=r′−r has degree less than n. If q=q′, the coefficient of xdeg(q−q′)+n in (q−q′)g is lc(q−q′)gn, which is not zero because gn is a unit. So deg((q−q′)g)≥n, a contradiction. Hence q=q′ and r=r′, and the algorithm returns the unique quotient and remainder of f by g.
Operation count. Line L3 does one inversion. Each step does one multiplication in line L6 and n multiplications and n subtractions in line L9. Line L10 does no arithmetic. With m−n+1 steps, the total is (2n+1)(m−n+1) operations in R and one inversion. ■