I want to partition an integer into $k$ integers all possible orderings. This can be done in the following way

integerPartitions[n_, {k_}] := Select[FrobeniusSolve[Table[1, {k}], n], FreeQ[#, 0] &]

For example,

integerPartitions[4, {2}]


{{1, 3}, {2, 2}, {3, 1}}

But this is very slow if the partition number is large as compared to IntegerPartitions, which gives partitions in reverse lexicographic order. For instance, integerPartitions[60, {5}] will take more than 4 seconds in my laptop in contrast to 0 seconds of IntegerPartitions[60, {5}].

So my question is: what would be the most efficient Mathematica code for this problem?

  • 4
    $\begingroup$ Can't you apply permutations to the results of IntegerPartitions ? $\endgroup$ Feb 12, 2013 at 14:00

2 Answers 2


This seems to be quite quick :

output = Flatten[Permutations /@ IntegerPartitions[60, {5}], 1]; // AbsoluteTiming
(* {0.245025, Null} *)

output // Dimensions
(* {455126, 5} *)

If order does matter, you are generating integer compositions. Integer compositions are related to the operation multichoose. You can use the Resource Functions IntegerCompositions, where 0 s are allowed like {0,0,5} for 5 into 3 parts, and StrictIntegerCompositions for this, where 0 s are not allowed like {2,1,2} for 5 into 3 parts.

  • $\begingroup$ Please add the specific code to be used to obtain the desired results $\endgroup$
    – MarcoB
    Aug 5, 2023 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.