Proofs: Sparse polynomial multiplication
These are the human proofs of Sparse polynomial multiplication, at full length.
The heap method returns the normalized product of two sparse polynomials full
This proof shows: correctness.
Let be a commutative ring and let and be lists that meet invariant (S): the exponents increase strictly and no coefficient is zero. The product is
Call a pair and its key. If or , the product is and line L1 returns the empty list, which is the list of . Assume now .
Claim 1. The heap holds at most one pair from each row. Line L2 puts the pair for each row . Line L9 pushes only right after it pops . So by induction, at each test of line L4 the heap holds, for each row , either nothing or the single pair , where is the number of pairs of row already popped. In particular the heap never has more than entries.
Claim 2. Every pair is popped exactly once. By Claim 1, the pairs of row are popped in the order , and after is popped the pair is pushed if . So all pairs of row are popped, each once, and then the row adds nothing more. The loop stops when the heap is empty, that is after all pairs are popped.
Claim 3. The keys are popped in nondecreasing order. Suppose line L5 pops a pair with key . Every pair still in the heap has a key at least , because the heap returns a minimum. Every pair that is pushed later comes after the pair that is now in the heap or was just popped, with , so , because . So all later pops have keys at least .
Claim 4. Before the final filter, lists, for each key value that occurs, one pair , in increasing order of . By Claim 3, the pairs with the same key are popped one after the other, with no other key between them. Lines L7 and L8 start a new term when the key differs from the last exponent of , and add the product to the last term when it is the same. So each block of equal keys gives one term, whose coefficient is the sum of the products of the block, and by Claim 2 each product is counted once. The exponents of increase strictly, because the keys do not decrease and a new term starts only when the key changes.
Conclusion. By Claim 4, equals the double sum above, which is . The terms of have strictly increasing exponents. Line L10 deletes the terms whose coefficient is : they contribute nothing to the sum, and the deletion keeps the order. So the result is the list of nonzero terms of the product in increasing order of exponent, which is the only list that meets (S) for that polynomial.