Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The following will build a binary tree, and then analyze it and extract the results:</p> <pre><code>Clear[intParts]; intParts[num_, elems_List] /; Total[elems] &lt; num := p[]; intParts[num_, {fst_, rest___}] /; fst &lt; num := {p[fst, intParts[num - fst, {rest}]], intParts[num, {rest}]}; intParts[num_, {fst_, rest___}] /; fst &gt; num := intParts[num, {rest}]; intParts[num_, {num_, rest___}] := {pf[num], intParts[num, {rest}]}; Clear[nextPosition]; nextPosition = Compile[{{pos, _Integer, 1}}, Module[{ctr = 0, len = Length[pos]}, While[ctr &lt; len &amp;&amp; pos[[len - ctr]] == 1, ++ctr]; While[ctr &lt; len &amp;&amp; pos[[len - ctr]] == 2, ++ctr]; Append[Drop[pos, -ctr], 1]], CompilationTarget -&gt; "C"]; Clear[getPartitionsFromTree, getPartitions]; getPartitionsFromTree[tree_] := Map[Extract[tree, #[[;; -3]] &amp;@FixedPointList[nextPosition, #]] &amp;, Position[tree, _pf, Infinity]] /. pf[x_] :&gt; x; getPartitions[num_, elems_List] := getPartitionsFromTree@intParts[num, Reverse@Sort[elems]]; </code></pre> <p>For example, </p> <pre><code>In[14]:= getPartitions[200,Prime~Array~150]//Short//Timing Out[14]= {0.5,{{3,197},{7,193},{2,5,193},&lt;&lt;4655&gt;&gt;,{3,7,11,13,17,19,23,29,37,41}, {2,3,5,11,13,17,19,23,29,37,41}}} </code></pre> <p>This is not insanely fast, and perhaps the algorithm could be optimized further, but at least the number of partitions does not grow as fast as for <code>IntegerPartitions</code>.</p> <p>Edit:</p> <p>It is interesting that simple memoization speeds the solution up about twice on the example I used before:</p> <pre><code>Clear[intParts]; intParts[num_, elems_List] /; Total[elems] &lt; num := p[]; intParts[num_, seq : {fst_, rest___}] /; fst &lt; num := intParts[num, seq] = {p[fst, intParts[num - fst, {rest}]], intParts[num, {rest}]}; intParts[num_, seq : {fst_, rest___}] /; fst &gt; num := intParts[num, seq] = intParts[num, {rest}]; intParts[num_, seq : {num_, rest___}] := intParts[num, seq] = {pf[num], intParts[num, {rest}]}; </code></pre> <p>Now, </p> <pre><code>In[118]:= getPartitions[200, Prime~Array~150] // Length // Timing Out[118]= {0.219, 4660} </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. 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