Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of different groups of N integers that sum up to A

I want to calculate the number of different ordered groups of N integers so that the elements of each group sums up to A

For instance: if N = 3 and A = 3 the result should be 10:
1 = [3, 0, 0]
2 = [2, 1, 0]
3 = [1, 2, 0]
4 = [0, 3, 0]
5 = [2, 0, 1]
6 = [1, 1, 1]
7 = [0, 2, 1]
8 = [1, 0, 2]
9 = [0, 1, 2]
10 = [0, 0, 3]

the way I did it was by brute-force:

public static int calc(int a, int n){
    if (n <= 1 || a == 0) return 1;

    int sum = 0;
    for (int i=0; i<=n; i++)
        sum += calc(a - i, n - 1);

    return sum;
}

i suspect that there can be a better way (some mathematical calculation that I missing..) is there?

EDIT In the original question i forgot to take into consideration the order

like image 227
bennyl Avatar asked Oct 12 '12 10:10

bennyl


1 Answers

This is combinatorial composition of A into N parts (including zero parts). Number of compositions for pair (A, N) is equal to C(A + N - 1, A), where C() is combination number aka binomial coefficient. See the same formula here and here

like image 171
MBo Avatar answered Sep 18 '22 13:09

MBo