Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, there is a way. Consider the polynomial</p> <pre><code>(X + a[0]) * (X + a[1]) * ... * (X + a[n-1]) </code></pre> <p>Its coefficients are just the sums of the <code>k</code>-products, its degree is <code>n</code>, so you can calculate the sum of all <code>k</code>-products for all <code>k</code> simultaneously in O(n^2) steps.</p> <p>After <code>s</code> steps, the coefficient of X<sup>s-k</sup> is the sum of the <code>k</code>-products of the first <code>s</code> array elements. The <code>k</code>-products of the first <code>s+1</code> elements fall into two classes, those involving the <code>(s+1)</code><sup>st</sup> element - these have the form <code>a[s]*((k-1)</code>-product of the first <code>s</code> elements) - and those not involving it - these are the <code>k</code>-products of the first <code>s</code> elements.</p> <p>Code such that <code>result[i]</code> is the coefficient of X<sup>i</sup> (the sum of the <code>(n-i)</code>-products):</p> <pre><code>int *k_products_1(int *a, int n){ int *new, *old = calloc((n+1)*sizeof(int)); int d, i; old[0] = 1; for(d = 1; d &lt;= n; ++d){ new = calloc((n+1)*sizeof(int)); new[0] = a[d-1]*old[0]; for(i = 1; i &lt;= d; ++i){ new[i] = old[i-1] + a[d-1]*old[i]; } free(old); old = new; } return old; } </code></pre> <p>If you only want the sum of the <code>k</code>-products for one <code>k</code>, you can stop the calculation at index <code>n-k</code>, giving an O(n*(n-k)) algorithm - that's good if <code>k &gt;= n/2</code>. To get an O(n*k) algorithm for <code>k &lt;= n/2</code>, you have to organise the coefficient array the other way round, so that <code>result[k]</code> is the coefficient of X<sup>n-k</sup> (and stop the calculation at index <code>k</code> if you want only one sum):</p> <pre><code>int *k_products_2(int *a, int n){ int *new, *old = calloc((n+1)*sizeof(int)); int d, i; old[0] = 1; for(d = 1; d &lt;= n; ++d){ new = calloc((n+1)*sizeof(int)); new[0] = 1; for(i = 1; i &lt;= d; ++i){ new[i] = old[i] + a[d-1]*old[i-1]; } free(old); old = new; } return old; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload