I want to count the number of ways we can partition the number n, into k distinct parts where each part is not larger than m.
For k := 2 i have following algorithm:
public int calcIntegerPartition(int n, int k, int m) {
int cnt=0;
for(int i=1; i <= m;i++){
for(int j=i+1; j <= m; j++){
if(i+j == n){
cnt++;
break;
}
}
}
return cnt;
}
But how can i count integer partitions with k > 2? Usually I have n > 100000, k := 40, m < 10000.
Thank you in advance.
As @Dave alludes to, there is already a really nice answer to the simple restricted integer case (found here (same link as @Dave): Is there an efficient algorithm for integer partitioning with restricted number of parts?).
Below is a variant in
C++which takes into account the maximum value of each restricted part. First, here is the workhorse:As you can see
pStdCapis very similar to the linked solution. The one noticeable difference are the 2 additional checks at the top:And here is the function that sets up the recursion:
Explanation of the parameters:
nis the integer that you are partitioningmis the length of each partitionmyMaxis the maximum value that can appear in a given partition. (the OP refers to this as the threshold)Here is a live demonstration https://ideone.com/c3WohV
And here is a non memoized version of
pStdCapwhich is a bit easier to understand. This is originally found in this answer to Is there an efficient way to generate N random integers in a range that have a given sum or average?If you actually intend to calculate the number of partitions for numbers as large as 10000, you are going to need a big int library as
CountPartLenCap(10000, 40, 300) > 3.2e37(Based off the OP's requirement).